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
- Variables
- func CheckLocal(raw string) error
- func DefaultRegistrationPaths(getenv func(string) string) []string
- func Expiry(token string) (time.Time, bool)
- func Fingerprint(token string) string
- func KeepReloaded(ctx context.Context, c *Credentials, logger *log.Logger, every time.Duration)
- func KeepRenewed(ctx context.Context, c *Credentials, logger *log.Logger, every time.Duration, ...)
- func ValidSessionID(id string) bool
- func WriteTokenFile(path string, tf TokenFile) error
- type Client
- func (c *Client) Events(ctx context.Context, connected func(), fn func(Event)) error
- func (c *Client) Info(ctx context.Context) (string, error)
- func (c *Client) Messages(ctx context.Context, id string, limit int) ([]Message, error)
- func (c *Client) Running(ctx context.Context) (map[string]bool, error)
- func (c *Client) Sessions(ctx context.Context) ([]Session, error)
- func (c *Client) URL() string
- type Content
- type Credentials
- func (c *Credentials) Client() (*Client, error)
- func (c *Credentials) Expires() time.Time
- func (c *Credentials) Fingerprint() string
- func (c *Credentials) Health(now time.Time) string
- func (c *Credentials) HealthState(now time.Time) string
- func (c *Credentials) Loaded() bool
- func (c *Credentials) Reload() (changed bool, err error)
- func (c *Credentials) Renew(ctx context.Context, now time.Time) (renewed bool, err error)
- func (c *Credentials) URL() string
- type Event
- type Keyed
- type Match
- type Message
- type PairResult
- type Session
- type TokenFile
- type ToolState
Constants ¶
const ReloadEvery = time.Minute
ReloadEvery is how often KeepReloaded re-reads the token file.
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.
const RenewEvery = time.Hour
RenewEvery is how often KeepRenewed checks the token.
const TitlePrefix = "OC | "
TitlePrefix starts the pane title of a TUI showing a session.
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.
const User = "opencode"
User is the HTTP Basic user every opencode credential goes with.
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 ¶
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.
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).
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 ¶
CheckLocal refuses a server URL that is not http://<loopback>:<port>.
func DefaultRegistrationPaths ¶
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 ¶
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 ¶
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
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 ValidSessionID ¶
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 ¶
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 ¶
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 ¶
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 ¶
Info is GET /api/info: the server's version (the one call that proves a credential without reading any session).
func (*Client) Messages ¶
Messages is session id's newest limit messages, OLDEST FIRST (GET /api/session/{id}/message, order=desc, reversed).
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 ¶
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).
type Keyed ¶
type Keyed struct {
Key string
Event cctranscript.Event
}
Keyed is one event of a message and its key within the message.
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 ¶
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.
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 ¶
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 ¶
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).
Source Files
¶
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. |