client

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 16 Imported by: ? 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.

README

hosts/client

The contract a front end is written against. A Client acts for one user and offers what a conversation UI needs: threads, runs, a resumable event stream, steering, cancelling, answering an approval or a question, and a thread's files.

go get github.com/7ar-chat/harness/hosts/client
c := client.HTTP("https://agent.example.com", token) // a remote harness server

th, _ := c.CreateThread(ctx, "")
run, _ := c.Send(ctx, th.ID, "Summarise the report", client.SendOptions{})
events, _ := c.Events(ctx, run.ID, 0) // AG-UI events; reconnects and resumes without a gap or a duplicate
for ev := range events {
    // ev.Type: TEXT_MESSAGE_CONTENT, TOOL_CALL_START, RUN_FINISHED, ...
}

Two implementations, one behaviour

client.HTTP(baseURL, token) speaks the JSON + Server-Sent Events API of a harness server (this module)
inproc.New(h, user) drives an engine in the same process (hosts/inproc, in the main module)

Both pass the same conformance suite (hosts/clienttest), so a front end written against Client behaves the same on either: a terminal UI (hosts/tui), a Slack bot, a desktop app. Swap one line to move from embedded to remote.

Errors and optional operations

Errors are *client.Error values with an HTTP status and a code; test them with errors.Is(err, client.ErrNotFound) and the other Err* values. A user never sees another user's threads: they are reported as ErrNotFound. Operations a server may lack (session history, slash commands, undo) are in client.Extras and return ErrNotSupported when absent.

The DTOs in this package are the wire format of the harness HTTP API: changing a JSON tag changes the API.

License

MIT. See LICENSE.

Documentation

Overview

Package client is the contract between a front end and the harness engine.

The engine is a library (package harness). A front end (the terminal UI, the web UI, a Slack bot, a desktop app) should not be written against it: it is written against Client, a narrow interface of what a conversation UI needs: threads, runs, a resumable event stream, steering, cancelling, answering an approval or a question, and a thread's files. Two implementations satisfy it and behave the same (clienttest.Run checks both):

  • hosts/inproc drives a harness.Harness living in the same process;
  • HTTP speaks the JSON + Server-Sent Events API served by hosts/httpapi, so a front end can attach to a remote harness-web.

A Client acts for one user: the in-process one is built for a login, the HTTP one authenticates with a bearer token. Threads and runs of other users are reported as ErrNotFound.

The DTOs below are the wire format of hosts/httpapi, which serves exactly these types; changing a JSON tag changes the HTTP API.

Index

Constants

View Source
const (
	ReasonToolApproval = store.ReasonToolApproval
	DecisionApprove    = store.DecisionApprove
	DecisionDeny       = store.DecisionDeny
	DecisionRespond    = store.DecisionRespond
)

Reasons of an interrupt and decisions of a tool approval.

View Source
const (
	RoleUser      = store.RoleUser
	RoleAssistant = store.RoleAssistant
	RoleTool      = store.RoleTool
)

Roles of a Message.

View Source
const (
	// ModeBuild is the default: all tools the profile allows.
	ModeBuild = "build"
	// ModePlan is read-only: the agent investigates and proposes a plan, and no tool may change files or run mutating commands.
	ModePlan = "plan"
)

Run modes of SendOptions.Mode.

Variables

View Source
var (
	ErrUnauthenticated = &Error{Status: 401, Code: "unauthenticated", Message: "Authentication required."}
	ErrNotFound        = &Error{Status: 404, Code: "not_found", Message: "Not found."}
	ErrConflict        = &Error{Status: 409, Code: "conflict", Message: "Conflict."}
	ErrInvalidRequest  = &Error{Status: 400, Code: "invalid_request", Message: "Invalid request."}
	ErrInvalidPath     = &Error{Status: 400, Code: "invalid_path", Message: "Invalid path."}
	ErrRunNotActive    = &Error{Status: 409, Code: "run_not_active", Message: "The run no longer accepts messages."}
	ErrTooManySteers   = &Error{Status: 429, Code: "too_many_steers", Message: "Too many pending messages."}
	ErrNotSupported    = &Error{Status: 501, Code: "not_supported", Message: "The store has no session listing."}
	ErrNoSandbox       = &Error{Status: 501, Code: "no_sandbox", Message: "This server has no sandbox."}
	ErrTooLarge        = &Error{Status: 413, Code: "too_large", Message: "The file is too large to download."}
)

The errors a Client reports.

Functions

func TableLookup

func TableLookup(t *modelinfo.Table, hints ...string) func(id string) (ModelInfo, bool)

TableLookup is the WithModelInfo lookup over a price table; hints are the provider names to prefer, tried in order (the configured provider name, then its type).

Types

type ActiveRun

type ActiveRun = store.ActiveRun

ActiveRun, PendingQuestion, QuestionOption and ToolCall are the engine's own wire types, shared so that there is a single definition of them.

type Attachment

type Attachment struct {
	Name string `json:"name"`
	// MIME is the media type, e.g. image/png.
	MIME string `json:"mime"`
	// Data is the content (base64 on the wire).
	Data []byte `json:"data"`
}

Attachment is a file sent along with a message (an image pasted into the UI).

type Author

type Author struct {
	Login      string `json:"login"`
	Kind       string `json:"kind,omitempty"`
	OnBehalfOf string `json:"onBehalfOf,omitempty"`
	Name       string `json:"name,omitempty"`
	AvatarURL  string `json:"avatarUrl,omitempty"`
}

Author identifies the speaker of a user message. Kind is "user" or "supervisor"; a supervisor acts OnBehalfOf a user. Name and AvatarURL are filled in by servers that know their users.

type Client

type Client interface {
	// Models lists the model ids runs may use and the default one.
	Models(ctx context.Context) (ModelList, error)

	// CreateThread starts a conversation (an empty title is titled from the first message).
	CreateThread(ctx context.Context, title string) (*Thread, error)
	// ListThreads returns the user's threads, pinned first then newest (limit <= 0: 50; at most 200).
	ListThreads(ctx context.Context, limit int) ([]Thread, error)
	// GetThread returns a thread with its messages, pending approval or question and active run.
	GetThread(ctx context.Context, threadID string) (*Thread, error)
	// RenameThread changes the title and/or the pinned flag.
	RenameThread(ctx context.Context, threadID string, p ThreadPatch) (*Thread, error)
	// DeleteThread removes a thread and its runs.
	DeleteThread(ctx context.Context, threadID string) error

	// Send adds a user message to the thread and queues a run answering it.
	// Follow the run with Events.
	Send(ctx context.Context, threadID, text string, o SendOptions) (*Run, error)
	// GetRun returns a run's status.
	GetRun(ctx context.Context, runID string) (*Run, error)
	// Events streams the run's AG-UI events with Seq > after, then follows the
	// run live and closes the channel after its terminal event (RUN_FINISHED or
	// RUN_ERROR) or when ctx is done. The error reports a run that cannot be
	// streamed (ErrNotFound...). A broken connection is resumed from the last
	// seq received: the stream has no gap and no duplicate. When the connection
	// cannot be recovered the channel ends with a synthetic RUN_ERROR event
	// (code "stream_lost").
	Events(ctx context.Context, runID string, after int64) (<-chan Event, error)
	// Steer adds a message to a running run: the model sees it at its next step.
	// ErrRunNotActive when the run already ended.
	Steer(ctx context.Context, runID, text string) error
	// Cancel stops a run (a finished run is left alone).
	Cancel(ctx context.Context, runID string) error
	// Resume answers the interrupt a run ended with (a tool approval or an
	// ask_user question) and queues the run that continues the conversation.
	Resume(ctx context.Context, threadID string, r ResumeRequest) (*Run, error)

	// ListFiles lists a directory of the thread's workspace ("" is its root).
	ListFiles(ctx context.Context, threadID, path string) ([]File, error)
	// DownloadFile returns the content of a file of the thread's workspace.
	DownloadFile(ctx context.Context, threadID, path string) (*Download, error)

	// Sessions lists the saved conversations (ErrNotSupported without a durable store).
	Sessions(ctx context.Context, limit int) ([]Session, error)
}

Client is what a front end needs from a harness.

func HTTP

func HTTP(baseURL, token string, opts ...HTTPOption) Client

HTTP returns a Client for the API of a harness-web server at baseURL (for example "http://127.0.0.1:8080"). token is the bearer token the server requires ("" for none).

type Command

type Command struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Source is "project", "user", "skill" or "builtin".
	Source string `json:"source,omitempty"`
	// ArgHint is shown after the name, e.g. "<file>".
	ArgHint string `json:"argHint,omitempty"`
}

Command is a custom command or a skill invocable as /name.

type CompactResult

type CompactResult struct {
	// Compacted is false when there was nothing to summarise.
	Compacted    bool `json:"compacted"`
	TokensBefore int  `json:"tokensBefore,omitempty"`
	TokensAfter  int  `json:"tokensAfter,omitempty"`
}

CompactResult is the outcome of Compact.

type Download

type Download struct {
	Path string
	Name string
	Data []byte
}

Download is a file fetched from a thread's workspace.

type Error

type Error struct {
	// Status is the HTTP status the error maps to.
	Status  int    `json:"-"`
	Code    string `json:"code"`
	Message string `json:"message"`
	// contains filtered or unexported fields
}

Error is an API error: the same value whether it comes from the engine in process or from a server's {"error":{"code","message"}} answer. Test it with errors.Is against the Err* values.

func AsError

func AsError(err error) *Error

AsError returns err as an *Error (nil when it is not one).

func Errorf

func Errorf(sentinel *Error, format string, args ...any) *Error

Errorf returns a copy of sentinel with a specific message.

func Wrap

func Wrap(sentinel *Error, message string, err error) *Error

Wrap returns sentinel's status and code with message and err as the cause errors.Unwrap reports. An engine-side Client uses it to keep the original error behind the API error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches errors of the same code.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the engine error behind an internal error.

type Event

type Event struct {
	Seq  int64
	Type string
	// Data is the full AG-UI event JSON (including its type and timestamp).
	Data json.RawMessage
}

Event is one AG-UI event of a run. Seq numbers the run's events from 1 and is the resume point of Events.

type Extras

type Extras interface {
	// Compact summarises the thread's history now (the automatic compaction runs by itself near the context limit).
	Compact(ctx context.Context, threadID string) (*CompactResult, error)
	// Undo removes the thread's last user message with the answers after it and restores the workspace
	// files to the snapshot taken before that run (a git workspace). The removed prompt is returned so the
	// UI can put it back in the input. Repeated calls walk back through the thread.
	Undo(ctx context.Context, threadID string) (*UndoResult, error)
	// Redo reapplies the last undone step (only after Undo, until a new message is sent).
	Redo(ctx context.Context, threadID string) (*UndoResult, error)
	// Fork copies the thread up to and including messageID ("" is the whole thread) into a new thread.
	Fork(ctx context.Context, threadID, messageID string) (*Thread, error)
	// Commands lists the custom commands (markdown prompt templates) and skills a user can invoke by name.
	Commands(ctx context.Context) ([]Command, error)
	// ExpandCommand returns the prompt of "/name args" (the template with $ARGUMENTS and $1.. replaced).
	ExpandCommand(ctx context.Context, name, args string) (string, error)
}

Extras are the operations beyond the core Client contract. A front end checks for them with a type assertion (c.(client.Extras)); an implementation or a server that lacks one answers ErrNotSupported, so a newer front end still works against an older server. Both inproc.New and HTTP implement it.

type File

type File struct {
	Name       string    `json:"name"`
	Path       string    `json:"path"`
	Type       string    `json:"type"` // "file" or "directory"
	Size       int64     `json:"size"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

File is an entry of a thread's workspace.

type HTTPOption

type HTTPOption func(*httpClient)

HTTPOption configures HTTP.

func WithBackoff

func WithBackoff(min, max time.Duration) HTTPOption

WithBackoff sets the wait between reconnections of an event stream: it starts at min and doubles up to max (defaults 200 ms and 5 s).

func WithHTTPClient

func WithHTTPClient(c *http.Client) HTTPOption

WithHTTPClient sets the http.Client used for requests (default: one without an overall timeout, as event streams are long-lived). Its Timeout must be zero.

func WithMaxReconnects

func WithMaxReconnects(n int) HTTPOption

WithMaxReconnects sets how many consecutive failed reconnections an event stream tolerates before it gives up (default 8). A reconnection that delivers an event resets the count.

type Message

type Message struct {
	ID         string         `json:"id"`
	RunID      string         `json:"runId,omitempty"`
	Role       string         `json:"role"`
	Content    string         `json:"content"`
	ToolCalls  []ToolCall     `json:"toolCalls,omitempty"`
	ToolCallID string         `json:"toolCallId,omitempty"`
	Error      string         `json:"error,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	CreatedAt  time.Time      `json:"createdAt"`
	// Author is who wrote a user message in a shared thread (nil for the
	// model's messages and for messages without a recorded author).
	Author *Author `json:"author,omitempty"`
}

Message is one message of a thread.

type ModelInfo

type ModelInfo struct {
	Provider      string `json:"provider,omitempty"`
	ContextWindow int    `json:"contextWindow,omitempty"`
	MaxOutput     int    `json:"maxOutput,omitempty"`
	// Priced is false when the model has no price (zero prices then mean unknown).
	Priced             bool    `json:"priced,omitempty"`
	InputPerToken      float64 `json:"inputPerToken,omitempty"`
	OutputPerToken     float64 `json:"outputPerToken,omitempty"`
	CacheReadPerToken  float64 `json:"cacheReadPerToken,omitempty"`
	CacheWritePerToken float64 `json:"cacheWritePerToken,omitempty"`
	// Tier lists the higher prices of prompts above Tier.Above tokens.
	Tier      *PriceTier `json:"tier,omitempty"`
	Vision    bool       `json:"vision,omitempty"`
	Reasoning bool       `json:"reasoning,omitempty"`
	Tools     bool       `json:"tools,omitempty"`
}

ModelInfo describes a model; a zero field is unknown. Prices are dollars per token.

func FromModelInfo

func FromModelInfo(i modelinfo.Info) ModelInfo

FromModelInfo converts a table entry to its wire form.

func (ModelInfo) Cost

func (m ModelInfo) Cost(in, out, cached, prompt int) (usd float64, ok bool)

Cost is the price in dollars of in input tokens (cached of them served from the prompt cache) and out output tokens (reasoning included); prompt is the largest single prompt, which selects the price tier (0: the base prices). ok is false when the model has no price.

type ModelList

type ModelList struct {
	Models  []string `json:"models"`
	Default string   `json:"default"`
	// Info describes the models it knows (context window, prices, capabilities),
	// by id; absent from servers that have no model table.
	Info map[string]ModelInfo `json:"info,omitempty"`
}

ModelList is the answer of Models.

type PendingQuestion

type PendingQuestion = store.PendingQuestion

ActiveRun, PendingQuestion, QuestionOption and ToolCall are the engine's own wire types, shared so that there is a single definition of them.

type PriceTier

type PriceTier struct {
	Above      int     `json:"above"`
	Input      float64 `json:"input,omitempty"`
	Output     float64 `json:"output,omitempty"`
	CacheRead  float64 `json:"cacheRead,omitempty"`
	CacheWrite float64 `json:"cacheWrite,omitempty"`
}

PriceTier is the price list of prompts above Above tokens (dollars per token).

type QuestionOption

type QuestionOption = store.QuestionOption

ActiveRun, PendingQuestion, QuestionOption and ToolCall are the engine's own wire types, shared so that there is a single definition of them.

type ResumeRequest

type ResumeRequest struct {
	// InterruptID is the interrupt's id (the approval id for a tool approval).
	InterruptID string `json:"interruptId"`
	// Reason is the interrupt reason: ReasonToolApproval or "ask_user" (inferred from Decision when empty).
	Reason string `json:"reason,omitempty"`
	// Decision applies to tool approvals: DecisionApprove, DecisionDeny or DecisionRespond.
	Decision string `json:"decision,omitempty"`
	// Always approves the tool for the rest of the run chain.
	Always bool `json:"always,omitempty"`
	// Text is the answer to an ask_user question, or the free text of a respond.
	Text string `json:"text,omitempty"`
	// Model, ReasoningEffort and Interactive are the settings of the resumed run.
	Model           string `json:"model,omitempty"`
	ReasoningEffort string `json:"reasoningEffort,omitempty"`
	Interactive     bool   `json:"interactive,omitempty"`
	// Mode is ModeBuild or ModePlan ("": the mode of the thread's previous run).
	Mode string `json:"mode,omitempty"`
}

ResumeRequest answers the interrupt a run ended with (POST /threads/{id}/resume).

type Run

type Run struct {
	ID        string    `json:"id"`
	ThreadID  string    `json:"threadId"`
	Status    string    `json:"status"`
	Model     string    `json:"model"`
	Error     string    `json:"error,omitempty"`
	ErrorCode string    `json:"errorCode,omitempty"`
	LastSeq   int64     `json:"lastSeq"`
	CreatedAt time.Time `json:"createdAt"`
	// Sandbox is the sandbox mode of the run: auto, off or on.
	Sandbox string `json:"sandbox,omitempty"`
}

Run is one execution of the agent.

type RunRequest

type RunRequest struct {
	Message string `json:"message"`
	SendOptions
}

RunRequest is the body of the run-creation request (POST /threads/{id}/runs).

type SendOptions

type SendOptions struct {
	// Model is the model id (default: the server's default model).
	Model string `json:"model,omitempty"`
	// ReasoningEffort is low|medium|high|... ("" for the model's default).
	ReasoningEffort string `json:"reasoningEffort,omitempty"`
	// Skills are skill names requested explicitly for this run.
	Skills []string `json:"skills,omitempty"`
	// Interactive makes risky tool calls wait for a decision (Resume).
	Interactive bool `json:"interactive,omitempty"`
	// Mode is ModeBuild (default) or ModePlan (read-only investigation).
	Mode string `json:"mode,omitempty"`
	// Attachments are files (images) sent with the message.
	Attachments []Attachment `json:"attachments,omitempty"`
	// Sandbox is auto (default: sandbox tools when the server has a backend, created on first use), off (no
	// sandbox tools for this run) or on (fail when the server has no sandbox).
	Sandbox string `json:"sandbox,omitempty"`
}

SendOptions are the per-run settings of Send; they are also the optional fields of the run-creation request.

type Session

type Session struct {
	ID         string    `json:"id"`
	Title      string    `json:"title"`
	Preview    string    `json:"preview"`
	Messages   int       `json:"messages"`
	LastStatus string    `json:"lastStatus"`
	Pinned     bool      `json:"pinned"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
}

Session is a saved conversation.

type Thread

type Thread struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Pinned    bool      `json:"pinned"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	// ActiveRun is the run in progress, nil when the thread is idle.
	ActiveRun *ActiveRun `json:"activeRun"`
	// PendingApproval is the risky tool call waiting for a decision (id,
	// toolName, arguments...), nil when there is none. Its "id" is the
	// InterruptID of the Resume answering it.
	PendingApproval map[string]any `json:"pendingApproval"`
	// PendingQuestion is the ask_user question waiting for an answer.
	PendingQuestion *PendingQuestion `json:"pendingQuestion"`
	Messages        []Message        `json:"messages,omitempty"`
}

Thread is a conversation. Messages is set by GetThread only.

type ThreadPatch

type ThreadPatch struct {
	Title  *string `json:"title,omitempty"`
	Pinned *bool   `json:"pinned,omitempty"`
}

ThreadPatch changes a thread; nil fields stay as they are.

type ToolCall

type ToolCall = store.ToolCall

ActiveRun, PendingQuestion, QuestionOption and ToolCall are the engine's own wire types, shared so that there is a single definition of them.

type UndoResult

type UndoResult struct {
	// Prompt is the user message that was removed (Undo) or restored (Redo).
	Prompt string `json:"prompt"`
	// Files are the workspace paths whose content changed; empty when the workspace is not a git repository.
	Files []string `json:"files,omitempty"`
	// CanUndo and CanRedo tell whether another step is available.
	CanUndo bool `json:"canUndo"`
	CanRedo bool `json:"canRedo"`
}

UndoResult is the outcome of Undo and Redo.

Jump to

Keyboard shortcuts

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