tuihost

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 51 Imported by: 1 module, 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

Index

Constants

View Source
const (
	LoginCodeBadParams       = 4000
	LoginCodeMissing         = 4001
	LoginCodeManaged         = 4006
	LoginCodeUnknownProvider = 4010
	LoginCodeAuthType        = 4011
	LoginCodeBadValue        = 4012
	LoginCodeUnknownLogin    = 4013
	LoginCodeBadName         = 4014
	LoginCodeUnknownJob      = 4015
	LoginCodeNotWaiting      = 4016
	LoginCodeUnknownSession  = 4017
	LoginCodeBusy            = 4018
	LoginCodeStore           = 5140
)

Wire codes of refused login requests, the background service carrying the reason beside them

View Source
const (
	// Error code a client answers when none of its windows shows the session of the request
	NotShownCode = 4404
	// Refusal the tool reports once every attached client declined
	NotShownMessage = "No attached client is showing this chat, so the request is out of reach. " +
		"Ask the user to open this chat, then retry."
)
View Source
const AutoContinueNotePrefix = autoContinueNotePrefix

Opening of the system note an auto continued turn carries, shared with the gateway recovery notes

View Source
const CommentaryWithheld = "commentary_withheld"

Display metadata flag on a held turn's published reply whose commentary no projection shows

View Source
const MaxRecoveriesPerMinute = 10

Spurious stdin EOF recoveries allowed per minute before the reader gives up

View Source
const RoomMemberActivityHook = "on_room_member_activity"

Plugin hook a hosted room member's live runtime events are projected to

View Source
const SandboxNotFound = "File not found on the gateway host: the path may live inside the agent sandbox"

Detail of a 404 for a path that likely names a file inside the agent sandbox

View Source
const SessionOwnershipUnavailable = sessionOwnershipUnavailable

Refusal text shown when a claim errors before it proved the session unowned

View Source
const SessionSegmentsKey = "_turn_segments"

Session record key holding the segment cursor of the running prompt turn

Variables

View Source
var (
	ConnectorInvalidParams         = ConnectorRefusalSpec{4000, "invalid_params", "Connector parameters are invalid."}
	ConnectorInvalidAnswer         = ConnectorRefusalSpec{4002, "invalid_answer", "Connection answer is invalid."}
	ConnectorUnknownOperation      = ConnectorRefusalSpec{4004, "unknown_operation", "No open operation with that op_id."}
	ConnectorUnknownTargetRefusal  = ConnectorRefusalSpec{4004, "unknown_target", "No such target on the open operation."}
	ConnectorConnectorsUnavailable = ConnectorRefusalSpec{4031, "connectors_unavailable", "Connectors are not available in this session."}
	ConnectorRequestFailed         = ConnectorRefusalSpec{5034, "connector_request_failed", "Connector request failed. Try again explicitly."}
	ConnectorReissueRefused        = ConnectorRefusalSpec{4002, "reissue_refused", "The target cannot be run again."}
	ConnectorReissueRefusals       = map[string]ConnectorRefusalSpec{
		tools.ConnUnknownTarget:  ConnectorUnknownTargetRefusal,
		tools.ConnMixedKinds:     {4000, "invalid_params", "One target kind per request."},
		tools.ConnLinkStillValid: {4002, "link_still_valid", "Reopen the stored link."},
		tools.ConnSettled:        {4002, "reissue_refused", "The operation has settled."},
		tools.ConnNotAllowed:     {4002, "reissue_refused", "This target cannot be run again."},
		tools.ConnRefused:        ConnectorReissueRefused,
	}
)

Connector refusals of the legacy handlers and the session authority's connection verbs

View Source
var (
	FanoutMaxPendingFrames = 16384
)

Bounds of one peer mailbox, the frame count and the serialized bytes it may hold unsent

View Source
var GatewayDocker struct {
	EnvActive    func(ctx context.Context) (bool, error)
	VolumeMounts func(ctx context.Context) ([][2]string, error)
}

Docker backend probes pkg/gateway owns, assigned by pkg/gateway at init

Functions

func AddKeyLogin

AddKeyLogin answers login.add_key, an API key stored as an owned login and never written to .env

func Advertise(transport Transport, serverRequests bool)

Records whether the client of a transport answers server to client requests

func AnswersRequests

func AnswersRequests(transport Transport) bool

True when the client of the transport advertised that it answers server to client requests

func AttachSessionTransport

func AttachSessionTransport(session *Session, transport Transport) bool

Attaches a transport to the session's peer set, true when it was not attached yet

func BindIdentity

func BindIdentity(isAuthenticated func(identity any) bool, ownerSubject func() string)

Installs the gateway functions that tell a signed in identity and name the host owner

func BindSinks

func BindSinks(write func(frame *jsonutil.Object), emit func(event, sid string, payload map[string]any), answerable func(sid string) bool,
	clients func(sid string) []Transport)

Binds the frame writer, the event emitter, the answerable check and, when given, the answering client lookup

func BindTransport

func BindTransport(ctx context.Context, transport Transport) context.Context

Context whose handlers write to the given transport

func Branch

func Branch(cwd string) string

Current branch name of the checkout, else its short head commit

func BridgedToolLabels

func BridgedToolLabels(ctx context.Context, name string, args map[string]any) []map[string]string

Labels of a call rendered as the payload maps gateway cards consume

func BroadcastGlobalEvent

func BroadcastGlobalEvent(event string, payload map[string]any, skip ...Transport)

Fans a session less event to every connected client, stdio when it is the client channel, else drops it

func BroadcastSessionEvent

func BroadcastSessionEvent(event, sid string, payload map[string]any)

BroadcastSessionEvent fans one session's event to every connected client with the session id on its frame, for a session whose own transport may already be gone

func BroadcastSkinIfChanged

func BroadcastSkinIfChanged(ctx context.Context)

Emits skin.changed when a skin moved, launch peers through the global broadcast and served homes to their own peers

func BuildImageRefMessage

func BuildImageRefMessage(userText string, imagePaths []string) string

Model message pointing the agent at each attached image so it runs vision_analyze in loop

func BuildPersistMessageWithImageRefs

func BuildPersistMessageWithImageRefs(userText string, imagePaths []string) string

Persisted user text with an image directive line per attached image after the caption

func BuildPersistUserMessage

func BuildPersistUserMessage(userText string, imagePaths []string, runMessage any) any

Persisted user turn shaped like the model payload with only its text part swapped for the image refs form

func CachedReaderSessionFields

func CachedReaderSessionFields(profilePath string, reader any, compute func() (map[string]any, error)) (map[string]any, error)

Session fields that also depend on the comparable reader key, reused while the store has not moved

func Cancel

func Cancel(sid *string, reason string, method *string) int

Withdraws the open requests of one session or of all when sid is nil, narrowed to one method when given

func CheckRequestParams

func CheckRequestParams(method string, params *jsonutil.Object) error

Refusal of the params a server request is about to carry, naming the field that does not fit its typed contract

func ClaimActiveSessionSlotRefusal

func ClaimActiveSessionSlotRefusal(ctx context.Context, sessionKey, liveSessionID, surface, profileHome string) (*activesessions.Lease, *activesessions.Refusal)

Claims the active lease for a surface, a reasonless ownership refusal when the claim itself errors

func ClaimParked

func ClaimParked(owns func(map[string]any) bool) []map[string]any

Parked events the owner predicate accepts in arrival order, each handed out to exactly one poller

func ClearParked

func ClearParked()

Empties the park and ends every held copy mark

func ClearTurnMarker

func ClearTurnMarker(home, sessionKey string)

Removes the marker once its turn concluded

func CoerceMessageText

func CoerceMessageText(content any, imageURLs bool) string

Plain string of message content keeping image URLs inline unless imageURLs is false

func CommentaryItems

func CommentaryItems(message map[string]any) []string

Commentary phase texts of an assistant row

func CommonRepoRoot

func CommonRepoRoot(cwd string) string

Main repository root of cwd folding linked worktrees, in git forward slash spelling

func ConnectorUIPayload

func ConnectorUIPayload(value any) any

Connector value with secret keyed entries replaced and every string redacted for a renderer

func ContentDisplayText

func ContentDisplayText(content any) string

Display text of message content with image parts as stand in labels and list parts joined by lines

func ConvertLogin

ConvertLogin answers login.convert, an env linked key moved into an owned login on explicit request

func DiagnoseStdinState

func DiagnoseStdinState() string

O_NONBLOCK and SO_RCVTIMEO state of fd 0 for crash log forensics

func DropSessionViewer

func DropSessionViewer(session *Session, transport Transport)

Drops one viewer registration of a session

func Emit

func Emit(ctx context.Context, event, sid string, payload map[string]any) bool

Emits one event for a session unless its presentation is muted, stamped with the running turn identity

func EmitRoomMemberActivity

func EmitRoomMemberActivity(ctx context.Context, hostedTask any, kind string, payload any, seq any) bool

Queues one activity event stamped with the room coordinates for every consumer, false when nobody listens

func EventFrame

func EventFrame(event, sid string, payload map[string]any) *jsonutil.Object

JSON RPC event notification of one event for a session, the payload key present only with a payload

func EventsSince

func EventsSince(sid string, lastSeen int) []*jsonutil.Object

Recorded event objects newer than lastSeen for a session, decoded outside the ring lock

func ExpandSkillInvocationForReplay

func ExpandSkillInvocationForReplay(ctx context.Context, text, taskID string) (out string)

Skill message a projected slash invocation expands back into, the text unchanged when not resolvable

func FittedAnswer

func FittedAnswer(method string, raw any) (*jsonutil.Object, error)

Answer a client gave a server request, refused with the field named when it does not fit the typed answer

func Forget

func Forget(transport Transport)

Drops the advertisement of a disconnected transport

func ForgetSession

func ForgetSession(sid string)

Releases a torn down session's replay ring so late frames are never retained again

func HandleSpuriousEOF

func HandleSpuriousEOF(recoveryTimes *[]float64, logFn func(string)) bool

Recovers a spurious empty read of stdin, true when the reader should continue and false on a genuine close or rate limit

func HistoryToMessages

func HistoryToMessages(ctx context.Context, history []any, profileHome string, imageURLs bool) ([]any, error)

Display projection of stored history rows, image parts rendered as stand in labels when imageURLs is false

func IsDisplayHiddenMarker

func IsDisplayHiddenMarker(role, text string) bool

Whether a row is a gateway system notice persisted as a user row that must never render as a bubble

func IsResponseFrame

func IsResponseFrame(obj any) bool

True for a client response, an object with an id and a result or error member and no method

func IsSensitiveFilename

func IsSensitiveFilename(name string) bool

Whether a basename is an env file or a credential store, case insensitive

func IsSensitivePath

func IsSensitivePath(p string) bool

Whether the basename is sensitive or any component is a credential directory

func IsStdioTransport

func IsStdioTransport(t any) bool

Whether a transport is the module stdio transport

func IsTextOnlyBusyPayload

func IsTextOnlyBusyPayload(content any) bool

Whether a busy submit carries only plain text and no attachment or media

func IsTruncated

func IsTruncated(sid string, lastSeen int) bool

True when frames between lastSeen and the oldest retained seq were evicted

func IsUnmappedContainerPath

func IsUnmappedContainerPath(ctx context.Context, raw, profileHome string) (unmapped bool)

Whether a path is a docker backend container path rather than a host path or a typo on the host

func LatestSeq

func LatestSeq(sid string) int

Highest stamped seq of a session, zero when unknown

func LeaseMetadata

func LeaseMetadata(liveSessionID string) map[string]any

Writer identity of a lease for one live session id

func LinkLogin

LinkLogin answers login.link, a linked login over an env var or another tool's login

func ListLogins

ListLogins answers login.list, every provider's logins with the session's, the default's and rotation's markers

func LoadCfg

func LoadCfg(ctx context.Context) map[string]any

Effective user config of the active profile without the defaults merge, empty on any failure

func LoginExhaustedWire

LoginExhaustedWire is the login.exhausted payload of an exhausted pinned login

func LoginTime

func LoginTime(epoch float64) *string

LoginTime is the RFC 3339 time of an epoch, nil when unknown

func NormalizeTodoState

func NormalizeTodoState(value any) *jsonutil.Object

Client safe full task plan snapshot of a decoded value, nil when malformed or the unused empty store

func NormalizeToolProgressMode

func NormalizeToolProgressMode(mode any, def string) string

Known tool progress mode of a raw config value, log kept as a gateway mode, else the default

func NoteSkinBroadcast

func NoteSkinBroadcast(ctx context.Context)

Syncs the watcher baseline after a skin broadcast so the watcher does not repaint it again

func OutputRiskPayload

func OutputRiskPayload(name string, kw map[string]any) map[string]any

Risk badge payload of a tool row from the risk metadata the executor attached, nil without metadata

func ParkNotification

func ParkNotification(evt map[string]any) bool

Retains an addressed event whose owner session is not live, false when the park cannot take it

func PendingKind

func PendingKind(sid string) string

Method of the oldest open request of a session, empty when it waits on nothing

func PollLoginOAuth

PollLoginOAuth answers login.oauth_poll, the sign in's output, prompt and result, answering or cancelling it first

func ProjectHistoryCommentary

func ProjectHistoryCommentary(ctx context.Context, messages []any, profileHome string) ([]any, error)

History rows with Codex commentary projected inside the owning profile's config and redaction scope

func ProjectRoomMemberActivity

func ProjectRoomMemberActivity(ctx context.Context, frame *jsonutil.Object, session func(sid string) *Session) bool

Fires the hook for an outgoing event or server request frame of a session that is running a room turn

func RearmLoginWaits

func RearmLoginWaits(ctx context.Context, sessions LoginSessions, db *state.SessionDB)

RearmLoginWaits arms again every retry a store's sessions had armed before this process started

func RecordTurnStart

func RecordTurnStart(home, sessionKey, prompt string, attempts int, autoContinue bool, notificationCategory string)

Persists the marker of a turn about to run with how many auto continues led to it

func RedactVerboseText

func RedactVerboseText(text string) string

Forced redaction of verbose trail text capped to the TUI budget

func RegisterLiveTransport

func RegisterLiveTransport(transport Transport)

Tracks a connected client transport for global broadcasts, a nil or already tracked one changing nothing

func RegisterSessionSettingsStore

func RegisterSessionSettingsStore()

RegisterSessionSettingsStore makes the session rows the store of every session's own settings in this process

func ReleaseKey

func ReleaseKey(key string, blocking bool)

Drops everything recorded under a private key, queued for the next lock holder when non blocking

func RemoveLogin

RemoveLogin answers login.remove, one login and only its own source

func RenameLogin

RenameLogin answers login.rename

func RenderDiff

func RenderDiff(text string, cols int) (string, bool)

Diff rendered by the agent rich output module, which upstream does not ship, so the client renders its own

func ReplayEpoch

func ReplayEpoch() string

Opaque token identifying this process's seq numbering

func RepoRoot

func RepoRoot(cwd string) string

Top level repository root of cwd, empty outside a repository

func ResetForTests

func ResetForTests()

Clears the open requests and the client advertisements between tests

func ResetLogin

ResetLogin answers login.reset, the limit one login or every login of a provider ran into forgotten

func ResolveResponse

func ResolveResponse(frame *jsonutil.Object, transport Transport) bool

func ResolveResponseOf

func ResolveResponseOf(frame *jsonutil.Object, transport Transport) bool

Routes one client response frame to its open request, false when nothing waits for that id Settles an open sessionless request only when it was written to this transport, false for any other frame

func RosterStoreSignature

func RosterStoreSignature(profilePath string) []rosterFilePart

Stat parts of each session store file, nil without a store or while an mtime is still racy

func Send

func Send(ctx context.Context, method, sid string, params *jsonutil.Object, timeout *float64, qids []string) (*jsonutil.Object, error)

Sends one request and blocks for the result, nil when unanswered, a nil timeout waiting until settled

func SendAsync

func SendAsync(method, sid string, params *jsonutil.Object, onResult func(*jsonutil.Object)) (func(reason string), error)

Sends one request whose wait is owned elsewhere and returns the settle call that withdraws it if still open

func SerializeFrame

func SerializeFrame(obj *jsonutil.Object, peer string, log *slog.Logger) string

JSON text of a frame, an internal error frame carrying the original id when it cannot be serialized

func SessionAuthUserID

func SessionAuthUserID(session *Session) *string

Login a session was created under, its stamped slot or else the login of its transport

func SessionHasLiveTransport

func SessionHasLiveTransport(session *Session) bool

Whether a live peer transport is attached to the session

func SessionHasLiveTransportExcluding

func SessionHasLiveTransportExcluding(session *Session, excluding Transport) bool

Whether a session still has a live client other than the excluded transport, under the transport lock

func SessionLoginInfo

func SessionLoginInfo(ctx context.Context, poolKey string, choices provider.SessionLogins, activeID string) *tuigateway.SessionLogin

SessionLoginInfo is session.info's login for a session's current pool key, nil before the session has a route

func SessionLoginWait

SessionLoginWait answers session.login_wait, a retry of the last turn armed for the pinned login's reset, run at once, or dropped

func SetEventPresentationMuted

func SetEventPresentationMuted(muted func(ctx context.Context, event, sid string) bool)

Installs the predicate that mutes freeform events of the session whose turn is diagnostic only

func SetLoginDefault

SetLoginDefault answers login.set_default, the profile default login, exhaustion policy and rotation strategy

func SetLoginPriority

SetLoginPriority answers login.set_priority, a login moved to a place in the order its provider's logins are tried

func SetLoginRotation

SetLoginRotation answers login.set_rotation

func SetSessionLogin

SetSessionLogin answers session.set_login, one provider's login pin and exhaustion reaction stored with the session

func SetSessionViewer

func SetSessionViewer(session *Session, transport Transport, at float64)

Records a transport as a viewer of a session at the given wall clock time

func SettleBatch

func SettleBatch(locked *jsonutil.Object, frameResult any, ended string) *jsonutil.Object

Answers and outcome of a batch clarify, the tools/clarify_batch.py settle_batch rule

func SkillScaffoldProjection

func SkillScaffoldProjection(contentText string) string

Slash invocation a skill expanded turn came from, empty when the row is not one

func SkinHomeFor

func SkinHomeFor(profileID string) string

Profile home a peer's skin follows, empty for the launch home

func SkinPayload

func SkinPayload(ctx context.Context, cfg map[string]any) (payload map[string]any)

Skin event payload for the display.skin of a config, empty when the skin engine fails

func StampEvent

func StampEvent(obj *jsonutil.Object)

Stamps an outgoing event frame with its per session seq and records a frozen snapshot

func StampReplyFrame

func StampReplyFrame(segments *TurnSegments, event string, payload map[string]any) map[string]any

Payload with the turn identity when the event is a reply frame of a running turn, unchanged otherwise

func StampSessionFrame

func StampSessionFrame(session *Session, event string, payload map[string]any) map[string]any

Reply frame stamping with the cursor of the prompt turn the session record is running, if any

func StartLoginOAuth

StartLoginOAuth answers login.oauth_start, a device code or PKCE sign in running in the background whose link the client opens

func StdioIsRPCChannel

func StdioIsRPCChannel() bool

True when real stdout is the JSON RPC client channel

func SubagentEvent

func SubagentEvent(eventType string, name, preview any, kw map[string]any, showReasoning bool) (tuigateway.SubagentEventPayload, error)

Subagent event payload of an agent progress callback, the chain of thought dropped while reasoning is hidden

func SubagentPayload

func SubagentPayload(eventType string, name, preview any, kw map[string]any, showReasoning bool) (*jsonutil.Object, error)

Subagent event payload as the ordered object the session event stream publishes

func TodoStateFromHistory

func TodoStateFromHistory(history []map[string]any) *jsonutil.Object

Latest task plan snapshot of a loaded transcript, the newest result paired with an assistant plan tool call

func ToolCtx

func ToolCtx(name string, args map[string]any) (out string)

What a tool call asked for, whole, as its live and its stored row show it, empty when the preview cannot be built

func ToolResultText

func ToolResultText(result any) string

Redacted and capped plain text view of a tool result for the verbose trail

func TransportIsDead

func TransportIsDead(transport Transport) bool

Whether a transport is closed or its peer is gone

func UnholdParked

func UnholdParked(events []map[string]any)

Ends the held copy mark the park took for each event

func UnregisterLiveTransport

func UnregisterLiveTransport(transport Transport)

Stops tracking a transport on disconnect and drops the server requests it still owed an answer

func VisibleCommentary

func VisibleCommentary(ctx context.Context, text string) string

Commentary with think blocks stripped and secrets redacted under the context profile policy like live delivery

func WireLogin

func WireLogin(l provider.Login) tuigateway.LoginRow

WireLogin is the wire row of one login

func WriteJSON

func WriteJSON(ctx context.Context, obj *jsonutil.Object) bool

Writes one frame through the transport of its session, else the context bound one, else module stdio

Types

type ConnectorRefusalSpec

type ConnectorRefusalSpec struct {
	Code    int
	Reason  tuigateway.ConnectorErrorReason
	Message string
}

One connector refusal as both connector handlers send it, a wire code, a ConnectorErrorReason and a message

type DisplayMetadataError

type DisplayMetadataError struct{ Found string }

Display metadata that is set but is not a mapping, so no withheld flag can be read from it; Found names what it is instead

func (*DisplayMetadataError) Error

func (e *DisplayMetadataError) Error() string

func (*DisplayMetadataError) ErrorKind

func (e *DisplayMetadataError) ErrorKind() string

Kind label the error is logged under

type FanoutTransport

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

Ordered bounded per peer session event mailboxes, a slow peer losing its subscription on overflow

func NewFanoutTransport

func NewFanoutTransport(transports ...Transport) *FanoutTransport

Fanout over the given transports

func (*FanoutTransport) Attach

func (f *FanoutTransport) Attach(transport Transport) bool

Adds a peer, reusing a detached peer's writer for the same transport, false when already attached

func (*FanoutTransport) Close

func (f *FanoutTransport) Close()

Detaches every peer without closing their sockets

func (*FanoutTransport) Contains

func (f *FanoutTransport) Contains(transport Transport) bool

True when the transport is an attached peer

func (*FanoutTransport) Detach

func (f *FanoutTransport) Detach(transport Transport) bool

Detaches a transport, true when it was attached

func (*FanoutTransport) HasTransports

func (f *FanoutTransport) HasTransports(excluding Transport) bool

True when any attached transport other than excluding remains

func (*FanoutTransport) Transports

func (f *FanoutTransport) Transports() []Transport

Attached peer transports

func (*FanoutTransport) Write

func (f *FanoutTransport) Write(obj *jsonutil.Object) bool

Fans a frame out to every attached peer, true while any peer stays attached

func (*FanoutTransport) WriteOverflow

func (f *FanoutTransport) WriteOverflow(obj *jsonutil.Object, overflow func(Transport) *jsonutil.Object) bool

Fans a frame out, an overflowed peer getting the notice overflow returns or its transport closed

type HTTPError

type HTTPError struct {
	Status int
	Detail string
}

Status and detail of the error a file path helper raises

func FsPath

func FsPath(rawPath string, cwd *string, decodeFallback bool) (string, *HTTPError)

Resolved host path a raw path or file URL names, an HTTP 400 for an empty or invalid one

func FsRegularFile

func FsRegularFile(ctx context.Context, p, profileHome string) (string, fs.FileInfo, *HTTPError)

Resolved regular readable non sensitive file a path names with its stat, else the HTTP error

func (*HTTPError) Error

func (e *HTTPError) Error() string

type LiveSession

type LiveSession struct {
	SID     string
	Session *Session
}

One live session id with its record

func LiveSessions

func LiveSessions() []LiveSession

Live sessions in registration order, snapshotted under the registry lock

type LoginError

type LoginError struct {
	Code    int
	Reason  string
	Message string
}

LoginError is a refused login request with its wire code and the reason the background service reports

func LoginFailure

func LoginFailure(err error) *LoginError

LoginFailure is the refusal of a failed provider login call, its fault kind picking the code and a store failure otherwise

func (*LoginError) Error

func (e *LoginError) Error() string

type LoginSession

type LoginSession struct {
	// Id the client named
	ID string
	// Store holding the session row its login choices live on
	DB *state.SessionDB
	// Row the choices live on
	StoredID string
	// Pool key of the session's current route, empty before it has one
	PoolKey string
	// Login the live agent sends requests with, empty without one
	ActiveLoginID string
	// Hands the new choices to a live agent, which moves onto them at its next turn start
	Adopt func(provider.SessionLogins)
	// Tells the session's viewers its info changed
	Publish func(ctx context.Context)
	// Re-runs the session's last turn
	Retry func(ctx context.Context) error
}

LoginSession is one session a login request names, as the backend that owns it sees it

func (*LoginSession) Choices

Choices reads the session's own login choices from its stored row

type LoginSessions

type LoginSessions interface {
	LoginSession(ctx context.Context, sessionID string) (*LoginSession, error)
}

LoginSessions finds the session a login request names on one backend

type RequestParamsError

type RequestParamsError struct{ Problem string }

Params of a server request that its contract rejects, the ValueError of the sender

func (*RequestParamsError) Error

func (e *RequestParamsError) Error() string

type ServerRequest

type ServerRequest struct {
	ID     string
	SID    string
	Method string
	Params *jsonutil.Object
	// contains filtered or unexported fields
}

One question the backend asked the renderer, open until a response, a cancel or its deadline settles it

func (*ServerRequest) Frame

func (r *ServerRequest) Frame() *jsonutil.Object

JSON RPC request frame as sent to the client

func (*ServerRequest) Snapshot

func (r *ServerRequest) Snapshot() *jsonutil.Object

Open request entry for a reconnecting client, with the batch answers locked so far

type Session

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

Live session record, a dict of named slots that readers and writers on any goroutine share

func NewSession

func NewSession(fields map[string]any) *Session

Record holding a copy of the given slots

func PopSessionRecord

func PopSessionRecord(sid string) *Session

Removes and returns the live record of sid in one registry critical section, nil when absent

func SessionRecord

func SessionRecord(sid string) *Session

Record of a live session by id, nil when the process holds none

func SteerAuthoritySession

func SteerAuthoritySession(sid string, transport Transport, expected *Session) *Session

Live record under sid the transport is attached to, nil when absent, replaced by another record or detached

func (*Session) Fields

func (s *Session) Fields() map[string]any

Copy of every slot the record holds

func (*Session) Get

func (s *Session) Get(key string) any

Value of a slot, nil when the record or the slot is absent

func (*Session) Lookup

func (s *Session) Lookup(key string) (any, bool)

Value of a slot and whether the record holds it

func (*Session) Pop

func (s *Session) Pop(key string) (any, bool)

Removes a slot and returns the value it held

func (*Session) Set

func (s *Session) Set(key string, value any)

Stores a slot

func (*Session) SetDefault

func (s *Session) SetDefault(key string, def any) any

Value of a slot, storing the default first when the record lacks it

func (*Session) Update

func (s *Session) Update(fields map[string]any)

Stores every given slot under one lock

type SessionEntry

type SessionEntry struct {
	SID     string
	Session *Session
}

One live session with its id, the registry entry a transport detach returns

func DetachTransportFromSessions

func DetachTransportFromSessions(transport Transport) []SessionEntry

Detaches a transport from every session holding it, returning the sessions left with no live client

type SkinSignature

type SkinSignature struct {
	Name  string
	Mtime *float64
}

Active skin name and its user file mtime, nil mtime for a built in skin

func SkinSig

func SkinSig(ctx context.Context) SkinSignature

Active skin signature of the context profile

type StdioTransport

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

Writes JSON frames as lines to a stream resolved on every write

func NewStdioTransport

func NewStdioTransport(streamGetter func() io.Writer, lock *sync.Mutex) *StdioTransport

func (*StdioTransport) Close

func (t *StdioTransport) Close()

func (*StdioTransport) Write

func (t *StdioTransport) Write(obj *jsonutil.Object) bool

Writes one frame line and flushes it, false only when the peer is gone

type Transport

type Transport interface {
	Write(obj *jsonutil.Object) bool
	Close()
}

Peer a JSON RPC frame is forwarded to, Write false once the peer is gone

func CurrentTransport

func CurrentTransport(ctx context.Context) Transport

Transport bound to the request context, nil when none is bound

func DetachedWSTransport

func DetachedWSTransport() Transport

Parked sink a disconnected WebSocket session holds until it is resumed or reaped

func LiveTransports

func LiveTransports() []Transport

Transports of every connected peer a session less broadcast reaches, in registration order

func ModuleStdioTransport

func ModuleStdioTransport() Transport

Module stdio transport, the sink of a request no transport was bound for

func SessionViewersByAge

func SessionViewersByAge(session *Session) []Transport

Viewer transports of a session from the oldest registration to the most recent

type TurnSegments

type TurnSegments struct {
	TurnID  string
	Segment int
	Offset  int
	// contains filtered or unexported fields
}

Segment cursor of one turn, created at message start and advanced by every delta and seal

func NewTurnSegments

func NewTurnSegments() *TurnSegments

func (*TurnSegments) Delta

func (s *TurnSegments) Delta(text any) map[string]any

Identity fields of one delta, the offset then advanced past a text

func (*TurnSegments) Seal

func (s *TurnSegments) Seal() map[string]any

Identity fields of the interim that seals the current segment, the cursor then moved to the next one

func (*TurnSegments) Start

func (s *TurnSegments) Start() map[string]any

Identity fields of the turn start frame

type UnknownQuestionError

type UnknownQuestionError struct{ QuestionID string }

Question id a batch does not hold, the ValueError of a lock on it

type WSConn

type WSConn interface {
	SendText(ctx context.Context, text string) error
	Close(code int) error
}

Socket of one WebSocket peer, SendText returning once the frame is handed to the connection

type WSTransport

type WSTransport struct {

	// Served profile home whose skin this peer follows, nil for the launch home
	SkinHome *string
	// contains filtered or unexported fields
}

Per connection WebSocket transport, safe to write from any goroutine with batches kept in wire order

func NewWSTransport

func NewWSTransport(ws WSConn, peer string, authIdentity map[string]any) *WSTransport

Transport over a socket, peer naming it in logs and authIdentity carrying the verified login

func (*WSTransport) Abort

func (t *WSTransport) Abort()

Closes from any goroutine and drops the socket with 1011 once so the client reconnects and replays

func (*WSTransport) AuthIdentity

func (t *WSTransport) AuthIdentity() map[string]any

Server verified identity of the upgrade credential, the sole authority for who this peer acts as

func (*WSTransport) Close

func (t *WSTransport) Close()

Latches closed and cancels the pending token flush

func (*WSTransport) Closed

func (t *WSTransport) Closed() bool

Whether the transport latched closed

func (*WSTransport) Conn

func (t *WSTransport) Conn() WSConn

Socket under the transport, what a viewer the peer opens records its admission against

func (*WSTransport) WS

func (t *WSTransport) WS() WSConn

Socket this transport writes to, what sign out tracks a browser tab by

func (*WSTransport) Write

func (t *WSTransport) Write(obj *jsonutil.Object) bool

Buffers a streamed token or sends the frame behind every buffered token, waiting a bounded time for the wire

func (*WSTransport) WriteAsync

func (t *WSTransport) WriteAsync(obj *jsonutil.Object) bool

Sends buffered tokens and the frame as one batch and returns once it is on the wire

func (*WSTransport) WriteManyAsync

func (t *WSTransport) WriteManyAsync(frames []*jsonutil.Object) bool

Sends buffered tokens then the frames in order as one batch and returns once it is on the wire

func (*WSTransport) WriteManyIfCurrentAsync

func (t *WSTransport) WriteManyIfCurrentAsync(frames []*jsonutil.Object, isCurrent func() bool) bool

Sends a batch whose own frames stop once isCurrent turns false, tokens of other producers going out regardless

Jump to

Keyboard shortcuts

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