opencodehost

package
v0.109.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 25 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 opencodehost is muster-mirror's side of opencode v2's local server (docs/design/opencode.md): the pair token muster-mirror holds, the one client that reads the server's REST API and event stream with it, and the pairing step that mints the token in the first place.

🔴 READ-ONLY, BY CONSTRUCTION. Every request this package makes is a GET (Client.get, Client.stream), except the two calls that mint a token — POST /api/pair and the unauthenticated GET /auth/connect/{code} — which only Pair and Credentials.Renew make (Client.mint). A test in this package reads its source and fails when any other request is spelled (TestTheClientMakesOnlyGETsExceptTheMint), and another drives every path against a fake server and fails on any request outside that set.

🔴 THE TOKEN AND THE SERVER PASSWORD ARE NEVER PRINTED OR LOGGED. What a person reads names a token by Fingerprint only.

Index

Constants

View Source
const RenewBefore = 10 * 24 * time.Hour

RenewBefore is how long before its expiry a token is replaced (Credentials.Renew): a third of its life, so a host that is off for a week still renews in time.

View Source
const RenewEvery = time.Hour

RenewEvery is how often KeepRenewed checks the token.

View Source
const TitlePrefix = "OC | "

TitlePrefix starts the pane title of a TUI showing a session.

View Source
const TokenTTL = 30 * 24 * time.Hour

TokenTTL is a pairing token's lifetime upstream (SESSION_TTL_SECONDS in packages/server/src/auth.ts at 6ec5682): 30 days.

View Source
const User = "opencode"

User is the HTTP Basic user every opencode credential goes with.

View Source
const WarnBefore = 3 * 24 * time.Hour

WarnBefore is how close to its expiry a token is reported to the person (Health) even while no renewal has failed: renewal starts at RenewBefore, so a token this close has not been renewed for a week.

Variables

View Source
var ErrNotRenewable = errors.New("this opencode token has no token file, so it is not renewed: pair the host (muster-mirror opencode-pair)")

ErrNotRenewable: a fixed token (EnvCredentials) has no file to keep a new one in.

View Source
var ErrUnauthorized = errors.New("the opencode server refused the credential (401)")

ErrUnauthorized: the server refused the credential (401). For a pair token: it expired, or the server's password was rotated (which revokes every token at once).

View Source
var RegistrationNames = []string{"service-prod.json", "service.json"}

RegistrationNames are the registration file's names Pair looks for, in order: the Nix build's channel, then the default channels'.

Functions

func CheckLocal

func CheckLocal(raw string) error

CheckLocal refuses a server URL that is not http://<loopback>:<port>.

func DefaultRegistrationPaths

func DefaultRegistrationPaths(getenv func(string) string) []string

DefaultRegistrationPaths is where the registration file can be: each of RegistrationNames under $XDG_STATE_HOME/opencode, else ~/.local/state/opencode. nil when neither base is known.

func Expiry

func Expiry(token string) (time.Time, bool)

Expiry is when token stops being accepted: its "<expires>." prefix, Unix seconds (the upstream token is "<expires>.<base64url HMAC>"). false when token is not of that shape.

func Fingerprint

func Fingerprint(token string) string

Fingerprint names a token for a person without revealing it: the first 8 hex digits of its SHA-256. The only thing about a token any output of muster-mirror prints.

func KeepRenewed

func KeepRenewed(ctx context.Context, c *Credentials, logger *log.Logger, every time.Duration, now func() time.Time)

KeepRenewed renews c (Renew) now and every RenewEvery until ctx ends, logging each renewal and each failure by fingerprint only. It returns at once for a token that cannot be renewed (logging so).

func ValidSessionID

func ValidSessionID(id string) bool

ValidSessionID reports whether id is a session id this client asks about: "ses" and up to 125 more bytes of [0-9A-Za-z_-] (Session.ID's pattern is "^ses"; muster's wire bound is 128).

func WriteTokenFile

func WriteTokenFile(path string, tf TokenFile) error

WriteTokenFile replaces the token file at path with tf, whole and 0600 (atomicfile), creating its directory 0700 when missing.

Types

type Client

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

Client reads one opencode server.

func NewClient

func NewClient(base string, secret func() string) (*Client, error)

NewClient is a client of the server at base (CheckLocal), authenticating with secret() — a pair token, or (Pair only) the server password — read at each request, so a renewed token is used from the next request on.

func (*Client) Events

func (c *Client) Events(ctx context.Context, connected func(), fn func(Event)) error

Events reads the server's event stream until ctx ends or the stream does, calling fn for each frame in order; connected is called once the server has accepted the request (before any frame). It returns ErrUnauthorized for a refused credential, and otherwise the reason the stream ended.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (string, error)

Info is GET /api/info: the server's version (the one call that proves a credential without reading any session).

func (*Client) Messages

func (c *Client) Messages(ctx context.Context, id string, limit int) ([]Message, error)

Messages is session id's newest limit messages, OLDEST FIRST (GET /api/session/{id}/message, order=desc, reversed).

func (*Client) Running

func (c *Client) Running(ctx context.Context) (map[string]bool, error)

Running is the sessions running now (GET /api/session/active).

func (*Client) Sessions

func (c *Client) Sessions(ctx context.Context) ([]Session, error)

Sessions is every ROOT session the server knows (GET /api/session, parentID=null), newest first, at most maxSessionPages pages.

func (*Client) URL

func (c *Client) URL() string

URL is the server's base URL.

type Content

type Content struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
	// ID and Name: a tool call's.
	ID    string    `json:"id,omitempty"`
	Name  string    `json:"name,omitempty"`
	State ToolState `json:"state,omitempty"`
}

Content is one item of an assistant message's content: text, reasoning or tool.

type Credentials

type Credentials struct {
	// Path is the token file; "" only for a test's fixed token
	// (EnvCredentials), which cannot be renewed.
	Path string
	// contains filtered or unexported fields
}

Credentials is the pair token muster-mirror reads opencode with, and the file it lives in. Renew replaces it before it expires — a token can mint its own replacement (POST /api/pair is accepted with a token wherever the password is) — and writes the new one to the same file, 0600.

func EnvCredentials

func EnvCredentials(base, token string) (*Credentials, error)

EnvCredentials is a fixed token for the server at base (CheckLocal), never renewed. 🔴 FOR TESTS AND THE BROWSER SUITE'S FAKE HOST (cmd/muster-mirror's e2emirror build) ONLY: the daemon takes its token from the token file alone, because a token it cannot renew stops working, silently, 30 days on.

func LoadCredentials

func LoadCredentials(path string) (*Credentials, error)

LoadCredentials reads the token file at path (ReadTokenFile).

func (*Credentials) Client

func (c *Credentials) Client() (*Client, error)

Client is a client of the token's server that authenticates with the current token at each request, and reports what each authenticated read says about the token to Health (observe).

func (*Credentials) Expires

func (c *Credentials) Expires() time.Time

Expires is when the current token stops being accepted.

func (*Credentials) Fingerprint

func (c *Credentials) Fingerprint() string

Fingerprint names the current token for a person (the package's Fingerprint).

func (*Credentials) Health

func (c *Credentials) Health(now time.Time) string

Health is what the person must be told about the token at now, "" when nothing: that it EXPIRED; that it expires soon while renewal is FAILING (and why); or that it expires within WarnBefore. 🔴 THE ONE SPELLING: the rendered view of an opencode window shows it, and `-list -opencode` prints it, so a renewal that keeps failing is seen in muster, not only in a log.

func (*Credentials) HealthState

func (c *Credentials) HealthState(now time.Time) string

HealthState is Health's STATE, without the countdown: "" for nothing, else "expired", "refused", "unreachable: <why>", "failing: <why>" or "soon". It changes only when what the person must do changes, so a view redraws on it rather than on every tick of "expires in …".

func (*Credentials) Renew

func (c *Credentials) Renew(ctx context.Context, now time.Time) (renewed bool, err error)

Renew replaces the token when it expires within RenewBefore of now: it mints a new one with the current token, checks it outlives the old one, writes it to the token file (0600, whole) and only then uses it. renewed is false, with no error, when the token is not yet due.

🔴 THE FILE IS WRITTEN BEFORE THE NEW TOKEN IS USED: a muster-mirror that dies between the two restarts on the new token, never on one it has already replaced. Both tokens stay valid until their own expiry (tokens are stateless upstream), so the order costs nothing.

func (*Credentials) URL

func (c *Credentials) URL() string

URL is the server the token was minted by (a loopback url, not a secret).

type Event

type Event struct {
	ID   string          `json:"id"`
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

Event is one frame of the event stream (GET /api/event).

func (Event) SessionID

func (e Event) SessionID() string

SessionID is the session an event names (data.sessionID), "" for none.

func (Event) Status

func (e Event) Status() string

Status is a session.status event's status type (idle, busy, retry), "" for any other event.

type Keyed

type Keyed struct {
	Key   string
	Event cctranscript.Event
}

Keyed is one event of a message and its key within the message.

func Render

func Render(m Message) []Keyed

Render is m's settled events, in order.

type Match

type Match struct {
	// Session is the one root session the title names; "" for none.
	Session string
	// Title is the title as the pane shows it (prefix stripped).
	Title string
	// Truncated: the pane's title was cut ("…"), so it was a prefix match.
	Truncated bool
	// Why says why there is no session; "" when there is one.
	Why string
}

Match is how a pane title resolved: the session, or why none.

func MatchTitle

func MatchTitle(paneTitle string, sessions []Session) Match

MatchTitle resolves pane title paneTitle against sessions (the server's root sessions; a child, should one be passed, is never matched).

type Message

type Message struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	Time struct {
		Created   float64 `json:"created"`
		Completed float64 `json:"completed,omitempty"`
	} `json:"time"`
	// Text: user, synthetic, system, skill.
	Text string `json:"text,omitempty"`
	// Description: synthetic, system.
	Description string `json:"description,omitempty"`
	// Content, Finish and Error: assistant (Error also idle).
	Content []Content       `json:"content,omitempty"`
	Finish  string          `json:"finish,omitempty"`
	Error   json.RawMessage `json:"error,omitempty"`
	// Outcome: idle (succeeded, failed, interrupted).
	Outcome string `json:"outcome,omitempty"`
	// Name: skill. Command, Status: shell.
	Name    string `json:"name,omitempty"`
	Command string `json:"command,omitempty"`
	Status  string `json:"status,omitempty"`
}

Message is one entry of a session's messages (Session.Message.Info, a union keyed by Type), as much of it as muster reads. The union's members share their field names, so one struct holds every one of them.

type PairResult

type PairResult struct {
	Registration string
	URL          string
	TokenFile    string
	Fingerprint  string
	Expires      time.Time
	// Replaced is the fingerprint of the token the file held before, "" for
	// none.
	Replaced string
}

PairResult is what Pair did, for a person: nothing in it is a secret.

func Pair

func Pair(ctx context.Context, registrations []string, tokenFile string) (PairResult, error)

Pair mints a token from the server named by the first of registrations that exists and writes it to tokenFile (WriteTokenFile).

type Session

type Session struct {
	ID       string `json:"id"`
	ParentID string `json:"parentID,omitempty"`
	Title    string `json:"title,omitempty"`
	Time     struct {
		Created float64 `json:"created"`
		Updated float64 `json:"updated"`
	} `json:"time"`
}

Session is one opencode session (Session.Info), as much of it as muster reads.

type TokenFile

type TokenFile struct {
	URL   string `json:"url"`
	Token string `json:"token"`
}

TokenFile is what the token file holds: the server it was minted by and the token itself. JSON, mode 0600, written whole (atomicfile).

The URL is written by Pair from the server's own registration file, so the daemon finds the server without ever reading that file (which also holds the server password).

func ReadTokenFile

func ReadTokenFile(path string) (TokenFile, error)

ReadTokenFile reads the token file at path. It refuses a symlink, anything that is not a regular file, and a file group or others can read: the token reaches the whole opencode API.

type ToolState

type ToolState struct {
	Status string          `json:"status,omitempty"`
	Input  json.RawMessage `json:"input,omitempty"`
}

ToolState is a tool call's state: streaming (Input is the raw text so far), running, completed or error (Input an object).

Directories

Path Synopsis
Package opencodetest is a FAKE opencode v2 server for muster's tests and browser suite: the routes muster-mirror reads (shaped from upstream's packages/protocol/openapi.json at 6ec5682), HTTP Basic auth with user "opencode", and pair tokens signed the way upstream signs them (packages/server/src/auth.ts), so a token it issues has the real shape and lifetime.
Package opencodetest is a FAKE opencode v2 server for muster's tests and browser suite: the routes muster-mirror reads (shaped from upstream's packages/protocol/openapi.json at 6ec5682), HTTP Basic auth with user "opencode", and pair tokens signed the way upstream signs them (packages/server/src/auth.ts), so a token it issues has the real shape and lifetime.

Jump to

Keyboard shortcuts

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