chat

package
v0.3.21 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 36 Imported by: 0 modules, 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 is Flockdeck's own terminal chat client: the `flockdeck chat` subcommand, run inside a pane's pseudo-terminal, talking straight to a model API.

It exists so that a model reached over HTTP is a first-class agent rather than something Flockdeck shells out to. There is no wrapper CLI, no node and no Python: the pane runs this binary, and this binary speaks the vendor's own protocol. Everything Flockdeck does around a pane -- status, resume, the history overlay, a fan-out reading a plan -- is fed from in here using the machinery the `claude` CLI already drives, so the workspace has nothing new to learn.

Index

Constants

View Source
const NoPrompt = "(no prompt recorded)"

NoPrompt stands in for a conversation that says nothing about itself, the way the same label does for a Claude Code transcript.

Variables

View Source
var EndpointStore func(agent string) string

EndpointStore is asked for the address an agent talks to now -- its api.baseURL in the catalog, agents.json included -- where the one the chat started with could not be reached. It is a variable so that the catalog can supply it without the chat client depending on it; "" is the vendor's own.

View Source
var ErrBadFlags = errors.New("run `flockdeck chat -h` for the flags it takes")

ErrBadFlags means the command line was wrong. The flag set has already said which part of it, so this only points at where the rest is written down -- repeating the complaint would bury it.

View Source
var ErrHelpShown = errors.New("usage shown")

ErrHelpShown means the usage was asked for and printed: there is nothing wrong and nothing left to do.

View Source
var ErrKeyRefused = errors.New("the API refused the key")

ErrKeyRefused is an endpoint refusing a key it was asked to check.

View Source
var ErrUnreachable = errors.New("the endpoint could not be reached")

ErrUnreachable is an endpoint that could not be reached to be asked at all: nothing listening at the address, a host that does not exist. It says nothing about the key.

View Source
var KeyStore func(agent string) string

KeyStore is asked for an API key when the environment does not have one. It is a variable so that the credential store can supply it without the chat client depending on it, and so that a key reaches exactly one process: this one.

Functions

func CheckKey added in v0.2.3

func CheckKey(ctx context.Context, wire, baseURL, key string) error

CheckKey asks an endpoint whether it takes a key, by listing its models -- the one request every wire has that costs nothing and needs the key. It reports nil where the key was taken, an error wrapping ErrKeyRefused where it was refused, and any other error where the endpoint could not be asked.

The refusal carries the status and not the vendor's words, which for some vendors quote part of the key back.

func Dir

func Dir() (string, error)

Dir is where flockdeck chat keeps its transcripts.

func KeyFor added in v0.3.3

func KeyFor(o Options) (key, from string)

KeyFor is the key a pane started with these options would send, and where it comes from in words that never include it. It is the chat's own lookup, so that `flockdeck keys check` asks the endpoint about that key rather than one found in another order; KeyStore must be set for a stored key to count.

func Path

func Path(session string) string

Path returns the transcript for a session, or "" when there is nothing to read.

Emptiness counts as nothing, the same way it does for Claude Code: a pane that was opened and never prompted leaves a file behind with no conversation in it, and resuming that is not resuming anything.

func Replies

func Replies(session string, maxTurns int) []string

Replies returns what the model said in its last few turns, newest first and at most maxTurns of them.

This is the shape session.RecentReplies has, and for the same reason: it is where a fan-out finds the plan it is about to split up. An API pane's plan is then no different from any other agent's.

func Run

func Run(ctx context.Context, o Options) error

Run is the chat client: it holds one conversation until the user leaves, the input ends, or the context is cancelled.

Types

type AlwaysApprover

type AlwaysApprover interface {
	// AlwaysKey returns a key standing for every call the user would be
	// agreeing to, or "" when this call cannot be approved in bulk.
	AlwaysKey(args json.RawMessage) string
}

AlwaysApprover is implemented by a tool that can be approved once for a whole family of calls rather than one at a time.

It is an interface rather than a rule in the loop because what makes two calls the same family is the tool's own business: for `run_command` it is the command prefix, and nothing else in v1 offers it at all.

type Conversation

type Conversation struct {
	ID       string
	Cwd      string
	Summary  string
	Title    string
	Modified time.Time
	Messages int
	Size     int64
}

Conversation is a stored chat that can be resumed. It carries the same facts as a Claude Code conversation, so the history overlay can list the two side by side.

func Conversations

func Conversations(cwd string) ([]Conversation, error)

Conversations lists the stored chats belonging to a working directory, newest first. An empty cwd lists them all.

type Entry

type Entry struct {
	Type string    `json:"type"`
	TS   timestamp `json:"ts"`
	Text string    `json:"text"`
	// Tool names the tool a "tool" entry is the output of, and Call is what
	// the call acted on as it was drawn -- "read_file src/a.go" -- without
	// which the history could say what a tool returned but not what of.
	Tool string `json:"tool,omitempty"`
	Call string `json:"call,omitempty"`
	Cwd  string `json:"cwd,omitempty"`
	// Agent is the catalog id the conversation was held with. Every API
	// agent keeps its chats in the one folder, so without it a chat with one
	// agent reopens as another.
	Agent string `json:"agent,omitempty"`
	Model string `json:"model,omitempty"`
	In    int    `json:"in,omitempty"`
	Out   int    `json:"out,omitempty"`
}

Entry is one line of a chat transcript.

The three types are what the conversation is made of; the rest are additions that cost a few bytes a line and answer questions the file otherwise cannot: which directory the conversation belongs to, which model wrote an answer, and what it cost. A reader that knows only about type, ts and text is unaffected by them.

func ReadEntries

func ReadEntries(path string) ([]Entry, error)

ReadEntries reads a whole transcript. A line that does not parse is skipped rather than failing the read: the last line of a file being written to is half-written as often as not.

type Event

type Event struct {
	Kind     EventKind
	Text     string
	Call     ToolCall
	Usage    Usage
	Thinking Thinking
}

Event is one thing that happened while a turn streamed.

type EventKind

type EventKind int

EventKind is what a streamed event carries.

const (
	// EventText is a piece of the answer, as it arrives.
	EventText EventKind = iota
	// EventThinking is a piece of the model's reasoning, where a model returns
	// it. It is drawn differently and never recorded: it is the model working
	// something out, not what it decided.
	EventThinking
	// EventCall is a completed request to run a tool.
	EventCall
	// EventUsage is the token count for the turn, sent once, at the end.
	EventUsage
	// EventReasoning is a completed block of reasoning, to go back with the
	// answer in the next request.
	EventReasoning
	// EventNotice is something the user should know about how the answer is
	// being got -- not part of it, and never recorded.
	EventNotice
)

type Log

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

Log appends to one session's transcript.

It is written through on every entry rather than buffered, because the two things that read it -- a fan-out looking for a plan, the history overlay -- read it while the pane is still running, and an answer still sitting in a buffer is an answer they cannot see.

func OpenLog

func OpenLog(dir, session, cwd string) (*Log, error)

OpenLog opens a session's transcript for appending, creating it if need be.

func (*Log) Append

func (l *Log) Append(e Entry) error

Append records one entry.

func (*Log) Close

func (l *Log) Close() error

func (*Log) Path

func (l *Log) Path() string

Path is the file this log writes to.

type Message

type Message struct {
	Role Role
	Text string
	// Calls are the tools an assistant message asked for.
	Calls []ToolCall
	// Call is the call a tool message answers.
	Call ToolCall
	// Thinking is the reasoning an assistant message came with, kept only to
	// be handed back.
	Thinking []Thinking
}

Message is one entry in a conversation, in the single shape all three wires are translated from. Keeping one shape is what lets the transcript, the renderer and the tool loop be written once.

func Messages

func Messages(entries []Entry) []Message

Messages turns a transcript back into a conversation to resume from.

A tool's output comes back as part of what the user said rather than as the answer to a call, because the transcript records what was said and not the call ids the wires pair an answer with -- and an answer to a call that is not in the request is rejected outright by every one of them. Consecutive entries on the same side are joined for the same reason: an API that insists the two sides alternate should not be handed two user entries in a row.

type ModelChoice added in v0.2.3

type ModelChoice struct {
	ID   string
	Name string
	Note string
}

ModelChoice is one model /model offers.

type Options

type Options struct {
	// Agent is the catalog id of the agent this pane was started as. It names
	// the key to look for and is what the header says.
	Agent string
	Model string
	// DefaultModel is the one the agent's catalog entry falls back to when
	// nobody picks one. A resumed conversation that had gone on with another,
	// chosen with /model, is taken up with that one rather than put back on
	// the default.
	DefaultModel string
	// Models are what the agent's catalog entry offers, which /model lists and
	// picks from by number. Any other id can still be named.
	Models  []ModelChoice
	Session string
	Resume  bool
	// Task is the opening prompt, which arrives in the argv rather than being
	// typed, because typing into a program means guessing when it is ready.
	Task string

	// Wire, BaseURL and KeyEnv are the agent's APISpec, passed in rather than
	// looked up here: the chat client has no catalog of its own. A flag or a
	// variable can say them; otherwise `flockdeck chat` reads them from the
	// agent's catalog entry before it gets here.
	Wire      string
	BaseURL   string
	KeyEnv    []string
	MaxTokens int

	Cwd string
	// Dir is where transcripts are kept. Empty means the state directory,
	// which is where they belong; a test says otherwise.
	Dir string

	// API and Token are the pane's callback address and secret.
	API   string
	Token string

	In     io.Reader
	Out    io.Writer
	Width  int
	Colour bool

	// Tools are what the model can do besides talk. The loop below already
	// handles asking for a call, the approval, the lifecycle events and feeding
	// the answer back; the tools themselves are supplied from outside so that
	// they and the loop can be built apart.
	Tools []Tool

	// Signals delivers interrupts. Empty means the client subscribes to them
	// itself, which is what it does in a pane.
	Signals <-chan os.Signal
	// contains filtered or unexported fields
}

Options are what one run of the chat client needs. Everything here is either a command line flag or something the pane's environment already carries, so that `flockdeck chat` behaves the same run from a pane and run by hand.

func ParseArgs

func ParseArgs(args []string, out io.Writer) (Options, error)

ParseArgs turns the arguments of `flockdeck chat` into the options to run with.

It lives here rather than beside main so that what the command accepts is tested where it is defined. Every flag has an environment variable behind it, because a pane's argv is built from an agent's Spec -- which can say `--wire openai` as a literal argument, or put the same thing in the pane's environment through Spec.Env -- and neither should be the only way.

type Request

type Request struct {
	Model     string
	System    string
	Messages  []Message
	Tools     []Tool
	MaxTokens int
}

Request is one turn asked of a model.

type Role

type Role string

Role is who an entry in a conversation came from.

There are three rather than the four or five a given vendor names, because these are the ones the transcript records and every wire can express: a system prompt is a field on the request, not an entry in the conversation.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type Schema

type Schema struct {
	Description string
	// Params is the JSON Schema object for the arguments -- `{"type":"object",
	// "properties":{...}}`. A tool that takes none may leave it empty.
	Params json.RawMessage
}

Schema is a tool's arguments described as JSON Schema. Each wire translates it into the shape that vendor asks for; the schema itself is the same.

type Thinking added in v0.2.3

type Thinking struct {
	Text      string
	Signature string
	// Redacted is the opaque data of a block the server would not show.
	Redacted string
}

Thinking is one block of reasoning a model returned with its answer.

It is never drawn or recorded -- EventThinking carries what is shown -- and is kept for one reason: Anthropic's models that think by default refuse the next request of a tool loop when the reasoning that led to a call has been left out of it, and the signature is how the server knows it was not edited.

type Tool

type Tool interface {
	Name() string
	Describe() Schema
	// Approval returns the question to put to the user before the call runs,
	// or "" when the call needs no asking.
	Approval(args json.RawMessage) string
	Run(ctx context.Context, args json.RawMessage) (string, error)
}

Tool is one thing the model can do beyond talking. The chat loop knows only this much about a tool, so the loop and the tools it runs can be built apart.

type ToolCall

type ToolCall struct {
	// ID is the vendor's identifier for the call, which the answer must quote.
	// Gemini has none, so it is filled in from the name there.
	ID   string
	Name string
	// Args are the arguments as the model wrote them. They stay raw JSON all
	// the way to the tool because a tool's own schema is the only thing that
	// knows their shape.
	Args json.RawMessage
	// Signature is an opaque token a vendor attached to the call and wants
	// back with it: Gemini's thought signature, without which a model that
	// thought before calling refuses the request carrying the answer.
	Signature string
	// BadArgs is what the model wrote for its arguments where that was not
	// JSON, in which case Args is an empty object. The call is not run: the
	// model is told what was wrong with what it wrote, rather than being told
	// by the tool that it wrote nothing.
	BadArgs string
}

ToolCall is one tool the model asked for.

type Usage

type Usage struct {
	// In is every token of input read, however it was priced; CacheRead and
	// CacheWrite are the parts of it read from and written to a prompt cache,
	// which cost a fraction and a premium of the rest.
	In         int
	Out        int
	CacheRead  int
	CacheWrite int
	// Reasoning is the part of Out a thinking model spent reasoning, where
	// the API says how much that was.
	Reasoning int
}

Usage is what a turn cost in tokens.

func (*Usage) Add

func (u *Usage) Add(v Usage)

Add accumulates one turn's usage into a running total.

type Wire

type Wire interface {
	// Name is the wire's name as an agent's APISpec spells it.
	Name() string
	// Stream sends one request and calls emit for each event until the answer
	// is complete. A cancelled context ends the turn; emit is only ever called
	// from the calling goroutine.
	Stream(ctx context.Context, req Request, emit func(Event)) error
}

Wire speaks one vendor's HTTP protocol.

A wire's whole job is translation: it turns a Request into that vendor's JSON and its stream back into Events. It renders nothing, records nothing and runs no tools, which is why three of them fit in a few hundred lines each.

func NewWire

func NewWire(name, baseURL, key string) (Wire, error)

NewWire returns the wire named by an agent's APISpec.

The three names are the ones the catalog uses, and "openai" covers every OpenAI-compatible endpoint -- Ollama, LM Studio, vLLM, a gateway -- which is why a local model needs no code of its own, only a base URL.

Directories

Path Synopsis
Package tool is the set of tools the native API agent runs.
Package tool is the set of tools the native API agent runs.

Jump to

Keyboard shortcuts

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