chat

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: Apache-2.0 Imports: 7 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

Overview

Package chat defines the provider-neutral seam between a chat platform and switchboard's session router. Each platform (Slack, Google Chat) implements Adapter; the router (cmd/switchboard) owns the mapping from a conversation to a core-agent session and shuttles turns across the pkg/daemon contract. Keeping the platform specifics behind this interface is what lets Slack land first (Phase 1) and Google Chat follow (Phase 3) without touching the router.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("chat: no such conversation or message")
	ErrDenied   = errors.New("chat: the platform refused the operation")
)

ErrNotFound and ErrDenied classify a platform's refusal as permanent, so a caller can tell "this will never work" from "try again later". An Adapter wraps them alongside its own error (the platform's own wording stays in the message; only the classification is portable) when the platform reports a missing conversation or message, or refuses the operation outright — the bot is not in the channel, the channel is archived, the message belongs to someone else. Everything else is left unclassified and treated as transient.

View Source
var ErrNoInbound = errors.New("chat: this adapter has no inbound source")

ErrNoInbound is returned by Run on an adapter built without an inbound source — no Slack app token, no Google Chat subscription. Such an adapter posts and never receives, which is the shape an outbound-only deployment wants: a monitoring loop that sends digests needs none of the credentials, connections or event subscriptions that receiving does (#23).

It is a refusal, not a resting state. Whoever built the adapter knows it has nothing to run and should not call Run at all; this says so out loud rather than blocking forever on a source that does not exist.

View Source
var ErrUnsupported = errors.New("chat: operation not supported by this platform")

ErrUnsupported is returned by Update/Delete on a platform that cannot edit or remove an already-posted message. The router treats it as non-fatal and degrades to plain Send, so progress features never break a platform that lacks them.

Functions

func ChunkText

func ChunkText(text string, limit int) []string

ChunkText splits text into pieces of at most limit bytes for a platform that caps message length, so a long model turn becomes several ordered posts rather than a truncated one.

Four properties, in the order they matter:

  • A fenced code block is never left unbalanced. Every platform switchboard speaks to renders an unclosed ``` literally, so a split landing inside a block puts raw backticks on screen in both halves and loses the monospace in one — the failure this exists to prevent (#31). A piece left open is closed, and the next reopened with a marker of the same width, so each renders correctly alone. A break is never taken inside the marker itself either, which would leave a stray backtick that no amount of balancing can see.
  • Nothing is dropped but the line ending the break is taken on. The pieces rejoin into the original text, which matters most inside a code block: a swallowed blank line changes what the model actually wrote.
  • The break prefers the last line ending in the window, so a reply's block structure survives it.
  • A multi-byte rune is never split. Half a rune renders as a replacement character, which reads as corruption rather than continuation.

Text that already fits is returned whole, as a single-element slice, so a caller can treat the result uniformly.

The size bound holds while the limit leaves room for both markers and a rune between them: 2w+6 <= limit, where w is the widest run of backticks in the text. A piece continuing a block pays w+1 to reopen it and w+1 to close it again, and has to carry at least one rune — up to four bytes — or the loop stops making progress. Past that point a piece can exceed limit by the markers' cost, which is the better of the two failures: the alternative is a text no piece of which can be balanced. The governing quantity is the widest run rather than the limit alone — a wall of backticks defeats a 4096-byte ceiling as surely as a tiny one, though it takes two thousand of them.

func DecisionText added in v0.3.0

func DecisionText(d *Decision) string

DecisionText renders a Decision's options as prose, for the Reply body that carries it. Every platform gets this; only some also get buttons.

It exists so the fallback is written once, here, instead of once per adapter with a different idea of how to say the same thing — and so a Decision posted to a platform switchboard cannot collect an answer on is still a question a person can read and act on by other means.

func RuneBoundary

func RuneBoundary(s string, n int) int

RuneBoundary returns the largest index <= n that starts a rune, so a hard cut never splits a multi-byte character. Shared by everything in the adapters that cuts a string to a byte budget — the chunker here, and the clamps that fit text into a platform's fixed-size fields.

Types

type Adapter

type Adapter interface {
	// Name identifies the platform for logs and metrics ("slack",
	// "googlechat").
	Name() string

	// Run consumes the platform's event source (Slack Socket Mode,
	// Google Chat Pub/Sub) and dispatches each inbound turn to h. It
	// returns when ctx is cancelled or the source fails unrecoverably, and
	// ErrNoInbound immediately when the adapter was built without a source
	// at all — an egress-only adapter is a valid thing to have, but not a
	// thing to run.
	Run(ctx context.Context, h Handler) error

	// Send posts a reply into its originating conversation and returns a
	// ref to the posted message so it can later be updated or deleted. When
	// a reply spans multiple platform messages, the ref identifies the
	// first one.
	Send(ctx context.Context, r Reply) (MessageRef, error)

	// Update replaces the content of a previously posted message. It
	// returns ErrUnsupported on platforms that cannot edit messages, and
	// no-ops on a zero ref.
	Update(ctx context.Context, ref MessageRef, r Reply) error

	// Delete removes a previously posted message (e.g. a progress
	// placeholder once the real reply is ready). It returns ErrUnsupported
	// on platforms that cannot delete messages, and no-ops on a zero ref.
	Delete(ctx context.Context, ref MessageRef) error
}

Adapter is a single chat platform's ingress + egress. Run blocks, delivering inbound messages to h until ctx is cancelled; Send posts a reply back to the platform. Implementations live in pkg/chat/slack and pkg/chat/googlechat.

type CallerMode

type CallerMode string

CallerMode selects how a platform user maps onto the daemon's X-Asserted-Caller identity. It lives here rather than in one adapter because the choice is the same question on every platform, and the answer has to be consistent: the daemon keys per-caller credentials off whatever arrives, so two adapters asserting different forms for the same human would look like two people.

const (
	// CallerEmail asserts the sender's email address, which is the form
	// the daemon's per-caller credential lookup expects. An adapter that
	// cannot obtain one for a given turn falls back to the platform ID
	// rather than dropping the turn.
	CallerEmail CallerMode = "email"
	// CallerID asserts the raw platform user ID — a Slack U0123ABC, a
	// Google Chat users/1234567890 — with no lookup and no extra scope.
	CallerID CallerMode = "id"
)

func ParseCallerMode

func ParseCallerMode(s string) (CallerMode, bool)

ParseCallerMode validates a caller-mode string, reporting whether it named a mode.

type Command

type Command struct {
	// Channel is the platform channel/space the command applies to. Gateway
	// settings are channel-scoped, so a Command carries the channel rather
	// than a full conversation key.
	Channel string

	// Caller is the invoker's asserted-caller identity (for logging/authz).
	Caller string

	// Name is the command verb, lower-cased, e.g. "progress".
	Name string

	// Args are the remaining whitespace-separated tokens, e.g. ["status"].
	Args []string
}

Command is a normalized gateway control command — a platform's native slash command (Slack /switchboard, a Google Chat slash command) or a recognized mention subcommand (@switchboard progress status). Unlike a Message it never reaches the daemon: it configures the gateway itself. Adding a platform means mapping its native command surface onto this type; the router interprets Name/Args and never learns the platform.

type CommandChoices

type CommandChoices interface {
	// Choices returns the accepted argument values for the named command,
	// or nil when it takes none, is unknown, or is free-form.
	Choices(name string) []string
}

CommandChoices is an optional Handler capability: reporting the values a gateway setting accepts. It exists so an adapter can name those values in whatever way its platform affords — spelled out in the message text, or, on a platform whose interactive controls actually reach the app, offered as buttons that re-invoke HandleCommand with the chosen value as the single argument, exactly as typing it would have. The handler stays the authority on what a command means; the adapter learns only the surface, so no platform gains a special case in the router and no router vocabulary is hard-coded in an adapter.

It is asked outside a command too: the Google Chat adapter, its only caller today, uses it for the welcome a new space gets, which names the values before anyone has run anything. So a Handler that does not implement it (or returns nil for a command it has no fixed choices for) is not merely falling back to its own acknowledgment text — on that surface there is no acknowledgment, and whatever the adapter says instead names nothing. An adapter must still work without it, and a Handler that has a fixed list is better off reporting it.

type Decision added in v0.3.0

type Decision struct {
	// ID correlates the press with the question. Opaque, and echoed back
	// verbatim on the Press so the router can find what it was asking about.
	ID string

	// Options are the answers, in the order they should be offered. An empty
	// or one-option Decision is not a question; adapters should treat it as a
	// plain message, since a lone button is a thing to be clicked rather than
	// a thing to be decided.
	Options []DecisionOption
}

Decision is a question switchboard is asking the thread, together with the answers it will accept — the agent has stopped on something only a person can settle, and this is that something rendered as a choice.

It rides on a Reply rather than being its own outbound type because it *is* a message: it goes to a conversation, it has a body, and on a platform whose interactive controls do not reach switchboard it has to degrade to that body and nothing else. An adapter that ignores this field entirely still posts a readable question — Reply.Text names the options in prose — it just cannot collect the answer.

Nothing here knows what the question is about. The router builds a Decision out of whatever the daemon is asking and reads the answer back the same way; this package carries opaque strings so that adding a second kind of question later is not a change to every adapter.

func (*Decision) Deciding added in v0.3.0

func (d *Decision) Deciding() bool

Deciding reports whether this Decision is one worth rendering as a choice. Guarding on it rather than on nil-ness alone keeps an adapter from building an interactive surface out of a question with nothing to answer.

type DecisionOption added in v0.3.0

type DecisionOption struct {
	// Value is returned verbatim as Press.Option. Opaque to every adapter.
	Value string

	// Label is the button text, already sized for a button and already
	// specific — "Allow every git this session", not "allow-session-verb".
	// The person deciding is reading this and nothing else.
	Label string

	// Broad marks an answer whose effect outlives the question being asked:
	// the rest of a session, or longer. It is a request for friction, not a
	// styling hint — an adapter with a confirmation affordance should spend it
	// here, because these are the presses that are regretted, and the label
	// alone has one line in which to say why.
	Broad bool
}

DecisionOption is one answer: what to send back, and what to write on it.

type Handler

type Handler interface {
	// Handle processes one inbound message (an agent turn).
	Handle(ctx context.Context, msg Message) error

	// HandleCommand processes a gateway control command and returns a short,
	// human-readable acknowledgment for the adapter to surface to the invoker
	// (ephemerally for a slash command, or as a thread reply for a mention
	// subcommand). An error is returned only for an internal failure; an
	// unknown or malformed command yields a helpful ack, not an error.
	HandleCommand(ctx context.Context, cmd Command) (string, error)

	// HandlePress processes one answer to a Decision this handler posted.
	//
	// On the interface rather than in an optional capability, so that an
	// adapter which renders buttons cannot be paired with a handler that has
	// nowhere to send the presses — the failure would be a person clicking a
	// button and watching nothing happen, which is worse than the button
	// never appearing. An adapter with no interactive surface simply never
	// calls it.
	//
	// It must be safe to call more than once for the same press: platforms
	// redeliver, and people click twice.
	HandlePress(ctx context.Context, p Press) error
}

Handler receives normalized inbound turns and gateway commands. The router implements it; an Adapter calls Handle once per inbound message and HandleCommand once per recognized command.

type Message

type Message struct {
	// Conversation is the stable key the router maps onto a core-agent
	// session — a Slack channel+thread_ts, or a Google Chat space+thread.
	// Same Conversation across turns => same session.
	Conversation string

	// Channel is the platform channel/space the conversation lives in,
	// independent of thread — a Slack channel ID or a Google Chat space.
	// The router uses it for channel-scoped gateway settings (e.g. a
	// per-channel progress mode) that apply across every thread in the
	// channel.
	Channel string

	// Caller is the platform identity of the human who sent the message,
	// in the daemon's asserted-caller form (e.g. "alice@example.com").
	// The router forwards it as X-Asserted-Caller so the daemon attributes
	// the turn and resolves per-caller MCP credentials (W0).
	Caller string

	// Text is the message body with platform mention markup stripped.
	Text string
}

Message is one inbound turn from a chat platform, normalized across providers.

type MessageRef

type MessageRef struct {
	// Conversation echoes the Reply's conversation so the adapter can
	// locate the message (Slack needs the channel to edit or delete).
	Conversation string
	// ID is the platform message identifier (Slack message ts).
	ID string
}

MessageRef identifies a reply already posted to a conversation so the router can update or delete it later — the mechanism behind long-turn progress indicators and in-place status edits. It is opaque to the router; only the originating Adapter interprets ID (for Slack, the posted message's timestamp). A zero MessageRef (empty ID) means "no message" and is safe to pass to Update/Delete, which no-op on it.

type Press added in v0.3.0

type Press struct {
	// Conversation is the thread the question was asked in, in the same form
	// Message.Conversation takes, so the router can find the session it
	// belongs to without a lookup table of its own.
	Conversation string

	// Channel is the platform channel the conversation lives in.
	Channel string

	// Caller is the presser's asserted-caller identity — the same form
	// Message.Caller takes, resolved the same way. This is what gets recorded
	// as the approver, so an adapter must resolve it from the press itself and
	// never from whoever the surrounding message was addressed to.
	Caller string

	// DecisionID and Option echo the Decision's ID and the chosen
	// DecisionOption's Value.
	DecisionID string
	Option     string

	// Message refs the posted question, so it can be edited to record what was
	// decided. Zero when the platform did not say which message the press came
	// from, which costs the edit and nothing else.
	Message MessageRef
}

Press is one inbound answer: someone chose an option on a Decision switchboard posted. It is not a Message — it never becomes an agent turn, and it carries no text — but it arrives on the same inbound path and is attributed the same way, because who pressed the button is the entire point of asking in a thread rather than answering on the agent's behalf.

type Reply

type Reply struct {
	// Conversation echoes Message.Conversation so the adapter posts into
	// the originating thread.
	Conversation string

	// Text is the reply body in the platform's markup dialect (the
	// adapter is responsible for any final formatting).
	Text string

	// Kind classifies the reply so an adapter can render it in the
	// platform's idiom. The zero value (KindAnswer) is an agent turn.
	Kind ReplyKind

	// Usage is what the turn cost, for an adapter to render as a footer on
	// the reply. Nil — the usual case — means show nothing: the router only
	// populates it for an answer, and only when the operator opted in.
	Usage *Usage

	// Decision, when set, makes this reply a question with answers attached,
	// for an adapter to render as buttons. Nil on every other kind of reply.
	//
	// Text still says the whole thing, options included, because an adapter
	// that cannot offer buttons must still be able to post the question. An
	// adapter that can should render from here and let Text be the fallback
	// its platform shows in notifications.
	Decision *Decision
}

Reply is one outbound turn switchboard relays back into a conversation.

type ReplyKind

type ReplyKind string

ReplyKind classifies what a Reply *is*, so an adapter can present it in the platform's idiom rather than as one undifferentiated blob of text: a progress placeholder can render as a card with a spinner, an error notice in a warning colour, a command acknowledgment as a compact one-liner. It is deliberately provider-neutral — the router says what a message means and the adapter decides how that looks, which is the same division of labour as the rest of this seam. An adapter that ignores Kind entirely still behaves correctly: every Reply carries Text that says the same thing.

const (
	// KindAnswer is an agent turn — the answer itself. The zero value, so a
	// Reply built without a Kind is treated as content.
	KindAnswer ReplyKind = ""
	// KindProgress is the transient "working on it" placeholder posted on
	// wake and retired when the answer lands.
	KindProgress ReplyKind = "progress"
	// KindActivity names the tools an agent is currently running.
	KindActivity ReplyKind = "activity"
	// KindNotice is a gateway-level warning — a turn that could not run.
	KindNotice ReplyKind = "notice"
	// KindAck is a gateway command's acknowledgment (see Handler.HandleCommand).
	KindAck ReplyKind = "ack"
	// KindDecision is a question the thread has to answer before the agent can
	// go on — the one reply kind that expects something back. See Decision.
	//
	// It is also the kind of the *edit* that settles that question, which
	// carries no Decision: the answers are gone because there is nothing left
	// to answer, and the body says what was decided and by whom. An adapter
	// therefore renders a decision-less one as an ordinary message, and — this
	// is the part worth getting right — must take down whatever interactive
	// surface it built for the original. A button that survives the decision it
	// was for is worse than one that never rendered.
	KindDecision ReplyKind = "decision"
)

type TextFitter

type TextFitter interface {
	// FitsOneMessage reports whether text renders into a single message.
	FitsOneMessage(text string) bool
}

TextFitter is an optional Adapter capability: reporting whether a text fits in a single platform message once the adapter has rendered it. Send already splits anything longer across several messages, so this matters only to a caller that must keep one editable message — the outbound ingress appending to a running timeline, which rolls over into a new message rather than letting the platform truncate one. An Adapter that does not implement it simply never triggers that rollover.

type Usage

type Usage struct {
	// Model is the model that ran the turn, e.g. "gemini-3.7-flash".
	Model string
	// TokensIn and TokensOut are the turn's prompt and completion tokens.
	TokensIn, TokensOut int64
	// CostUSD is the turn's cost in US dollars.
	CostUSD float64
	// Latency is the turn's wall-clock duration.
	Latency time.Duration
}

Usage is the token and cost accounting for the turn a Reply carries. It is structured rather than pre-rendered because the platforms have genuinely different places to put it (a Block Kit context block, a Chat card footer) and may want to arrange it differently; Line is the shared one-line form both use today.

func (Usage) Line

func (u Usage) Line() string

Line renders the usage as one line of plain text — e.g. "gemini-3.7-flash · 5,000 in / 1 out · $0.0038 · 3.1s". A field the daemon did not report is left out rather than shown as a zero, so a partial report degrades to a shorter line; an empty Usage renders as "" and the adapter then shows no footer at all.

Directories

Path Synopsis
This file builds the Google Chat card (cardsV2) payloads the adapter can send instead of flat text.
This file builds the Google Chat card (cardsV2) payloads the adapter can send instead of flat text.
This file renders a model turn's markdown into Slack Block Kit blocks — the opt-in rich alternative to the flat mrkdwn text payload (see mrkdwn.go), giving structural primitives that plain mrkdwn can only approximate: real headers, dividers, nested rich_text lists, native table blocks, and blockquotes.
This file renders a model turn's markdown into Slack Block Kit blocks — the opt-in rich alternative to the flat mrkdwn text payload (see mrkdwn.go), giving structural primitives that plain mrkdwn can only approximate: real headers, dividers, nested rich_text lists, native table blocks, and blockquotes.

Jump to

Keyboard shortcuts

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