opencodehost

package
v0.140.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 27 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 (TestTheClientMakesOnlyGETsExceptTheMintAndTheReplies), 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 EventSkipped = "muster.skipped"

EventSkipped is the Type of the frame Events hands fn in place of an event it could not read whole (a line over maxEventLine): the stream goes on, and the reader knows something was missed.

View Source
const ReloadEvery = time.Minute

ReloadEvery is how often KeepReloaded re-reads the token file.

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 ErrAnswerRefused = errors.New("opencode refused the answer")

ErrAnswerRefused: the server refused the answer itself (400): the field cannot take it. Nothing was answered.

View Source
var ErrAskSettled = errors.New("opencode: the ask is no longer pending")

ErrAskSettled: the server says the ask is no longer pending (404 for a permission request, 404 or 409 for a form): it was answered, rejected or cancelled elsewhere. Nothing was answered.

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 KeepReloaded added in v0.135.0

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

KeepReloaded re-reads c's file (Reload) every `every` until ctx ends, logging each change by fingerprint only. It never renews the token. A file that appears after the start (c a PendingCredentials: the host was paired since) is picked up the same way as a renewed or re-paired one. A failure is logged when it first happens and again only when it changes, so a file that does not exist yet is not logged every `every`.

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 ValidFormID added in v0.138.0

func ValidFormID(id string) bool

ValidFormID reports whether id is a form id ("frm_…", Form.ID's pattern).

func ValidRequestID added in v0.138.0

func ValidRequestID(id string) bool

ValidRequestID reports whether id is a permission request id ("per…", Permission.ID's pattern "^per").

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 Ask added in v0.138.0

type Ask struct {
	Kind AskKind
	// ID is the request's ("per…") or form's ("frm_…") id; Session the session
	// that asks (a subagent's child session, possibly).
	ID, Session string
	// A permission request's action ("bash", "edit", …) and resources (the
	// command, the paths).
	Action    string
	Resources []string
	// A form's title and fields.
	Title  string
	Fields []Field
}

Ask is one pending permission request or form of a session.

type AskKind added in v0.138.0

type AskKind string

AskKind is what an Ask asks for.

const (
	// AskPermission is a permission request.
	AskPermission AskKind = "permission"
	// AskQuestion is a form the question tool raised.
	AskQuestion AskKind = "question"
	// AskForm is any other form (an MCP elicitation, a plugin's): shown, never
	// answered from muster.
	AskForm AskKind = "form"
)

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.

A line longer than maxEventLine does NOT end the stream: it is discarded as it is read (never held whole), its event is dropped, and fn is called with an Event of Type EventSkipped instead.

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) PendingAsks added in v0.138.0

func (c *Client) PendingAsks(ctx context.Context, id string) ([]Ask, error)

PendingAsks is session id's pending permission requests and forms (GET /api/session/{id}/permission and /form), requests first.

func (*Client) ReplyForm added in v0.138.0

func (c *Client) ReplyForm(ctx context.Context, session, formID string, answer map[string]any) error

ReplyForm answers form formID of session with answer: each field's key to its value (a label, or labels for a multiselect).

func (*Client) ReplyPermission added in v0.138.0

func (c *Client) ReplyPermission(ctx context.Context, session, requestID string, decision PermissionReply) error

ReplyPermission answers permission request requestID of session with decision: once or reject. "always" widens the session's rules past this one call, so muster never sends it — refused here, before a byte is sent.

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 PendingCredentials added in v0.135.0

func PendingCredentials(path string) *Credentials

PendingCredentials is a READER's credential for a token file that cannot be read yet (not paired, say): it holds no token (Loaded is false) until Reload finds a usable file at path. Only for a muster-mirror that never renews (-opencode-read-only): KeepReloaded then picks up the file tenant default's daemon or `muster-mirror opencode-pair` writes later.

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) Loaded added in v0.135.0

func (c *Credentials) Loaded() bool

Loaded reports whether c holds a token: false only for a PendingCredentials whose file has not yet been read.

func (*Credentials) Reload added in v0.135.0

func (c *Credentials) Reload() (changed bool, err error)

Reload re-reads the token file and, when it holds a different token, uses that one from now on. It never mints: it is how a READER of the file (a muster-mirror run with -opencode-read-only) follows the renewals another daemon writes. changed is false, with no error, when the file is unchanged. A file that cannot be read leaves the current token in use.

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) AskEvent added in v0.138.0

func (e Event) AskEvent() (raised *Ask, settled string, session string, ok bool)

AskEvent is what an event says about an ask: one raised (Raised), or one settled (Settled names it, by its id) — answered, rejected or cancelled, in the terminal or anywhere else. ok false: the event is about no ask.

func (Event) ParentOf added in v0.138.0

func (e Event) ParentOf() (session, parent string)

ParentOf is the parent a session.created event names for its session: "" for a root session, or any other 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 the status an event says its session has now: a session.status event's type (idle, busy, retry) — and, because the v2 server at 6ec5682 never publishes session.status (only its schema declares it; measured against a real `opencode serve`, testdata/abort-v2.0.32.sse), the turn's own lifecycle: session.execution.started is busy, and its one terminal event (succeeded, failed, interrupted; packages/core/src/session/ execution.ts) idle. "" for any other event.

type Field added in v0.138.0

type Field struct {
	Key         string `json:"key"`
	Type        string `json:"type"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Options     []struct {
		Value string `json:"value"`
		Label string `json:"label"`
	} `json:"options,omitempty"`
	Custom bool `json:"custom,omitempty"`
}

Field is one question of a form, as much of it as muster reads.

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 PermissionReply added in v0.138.0

type PermissionReply string

PermissionReply is a permission request's answer as upstream spells it.

const (
	PermissionOnce   PermissionReply = "once"
	PermissionAlways PermissionReply = "always"
	PermissionReject PermissionReply = "reject"
)

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