runtime

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package runtime owns the SSH server, session lifecycle, input dispatch, centralized effect application, and space registry.

Terminal protocol filtering for line-oriented SSH sessions.

Input pipeline (read this top to bottom)

  1. Byte stream (this file, readUserLine / readUserCommand): assemble logical lines, strip inline escapes, and recognize line ends. A line ends on \n, \r, or CSI Enter (key codes in csiEnterKeys with final u/~, SS3 ESC O M). SSHTerminal echoes typed bytes, erases on backspace, and prints "> " via InputPrompter after each frame (remote ECHO is often off). Enter echoes CR LF and the next "> " is on that new line. A placed input rectangle is painted with cursor addressing inside that rectangle instead, and Enter does not echo CR LF. Arrows, Home, and End move inside the line. Up and down recall history. Tab completes the scene command. Ctrl-L redraws. Bracketed paste is inserted as text. Ctrl-U clears the line, Ctrl-W deletes the previous word, Ctrl-Z and Ctrl-\ are ignored, Ctrl-C ends the session, and Ctrl-D on an empty line ends it too.
  2. Transport line filter (IsTerminalProtocolLine): discard whole lines that are unambiguous wire noise (KITTY_* markers, long base64, escape-shaped remnants, iTerm's "-- BEGIN CONDUCTOR --"). Those lines are assembled without local echo when the bytes are already buffered (a kitten write) or while a bootstrap window is open. Kitty's ssh kitten streams a tar from KITTY_DATA_START through KITTY_DATA_END; OK and every other line in that window are absorbed. A line with a space ends the window early and is kept as a command. Short tokens such as "OK" outside that window may still reach scene eligibility.
  3. Scene eligibility (dispatcher InputEligible + engine RunLoop): dispatch when the line matches Inputs, or line-mode OnLine / OnEmpty fallbacks. Other lines print "no such command". Empty lines are ignored unless OnEmpty is set on the scene.

RunLoop repeats step 2 as a guard; step 1 never returns obvious protocol lines from readUserCommand, but callers other than SSHTerminal may feed HandleInput directly.

Non-goals (ponytail ceilings)

Not a VT emulator. Submit codes live in csiEnterKeys and the SS3 (ESC O M) check. Add another only when a real client sends it; do not grow scene or dispatch logic for terminal quirks.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InputEligible

func InputEligible(exp *installation.Installation, scene components.SceneID, input string) bool

InputEligible reports whether input could dispatch in scene (exact key, first token, or line-mode OnLine / OnEmpty fallbacks). Lines that fail this check are not user commands for the current scene—for example terminal acknowledgements such as "OK" when the scene only defines greet/go/….

func IsTerminalProtocolLine

func IsTerminalProtocolLine(s string) bool

IsTerminalProtocolLine reports transport-level noise (not scene dispatch policy).

func NewActionContextForTest

func NewActionContextForTest(sess *Session, exp *installation.Installation, eng *Engine) components.ActionContext

NewActionContextForTest builds an action context for tests.

func ResolveInput

func ResolveInput(exp *installation.Installation, scene components.SceneID, input string) (components.ActionID, error)

ResolveInput maps a raw input token to an action id for the current scene.

func SetSessionTerminalForTest

func SetSessionTerminalForTest(sess *Session, t Terminal)

SetSessionTerminalForTest binds a terminal for broadcast fan-out in tests.

Types

type AccountConfig

type AccountConfig struct {
	Enabled  bool
	Users    map[string]string // username -> password (dev only)
	Accounts identity.AccountStore
}

AccountConfig enables password authentication (phase 8).

type AccountStore

type AccountStore = identity.PlaintextAccountStore

AccountStore is an alias for the dev plaintext account backend. Prefer identity.OpenFileAccountStore for production sites.

func NewAccountStore

func NewAccountStore() *AccountStore

NewAccountStore creates a dev-only plaintext account store.

type ActionHooks

type ActionHooks struct {
	Before func(sess *Session, action components.ActionID, line string) (string, error)
	After  func(sess *Session, action components.ActionID, result ApplyResult, err error)
}

ActionHooks optionally intercept action dispatch.

type Applier

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

Applier applies effects to session and shared state.

func NewApplier

func NewApplier(spaces *spaceRegistry, store identity.Store) *Applier

NewApplier constructs an effect applier.

func (*Applier) Apply

func (a *Applier) Apply(sess *Session, exp *installation.Installation, effects []components.Effect) (ApplyResult, error)

Apply mutates session and spaces according to effects. Only this function writes session.current and session.local.

func (*Applier) LoadPersisted

func (a *Applier) LoadPersisted(idn identity.Identity, key string) (any, bool, error)

LoadPersisted reads identity store into scene context helpers (not session local).

func (*Applier) SetAccountStore

func (a *Applier) SetAccountStore(s identity.AccountStore)

SetAccountStore enables RegisterAccount effects when password auth is enabled.

func (*Applier) SetLogger

func (a *Applier) SetLogger(l *slog.Logger)

SetLogger records privileged account events. Nil keeps those events quiet.

func (*Applier) Store

func (a *Applier) Store() identity.Store

Store returns the identity persistence backend.

type ApplyResult

type ApplyResult struct {
	Transitioned bool
	Broadcast    []components.SpaceID
}

ApplyResult summarizes effect application for hooks and metrics.

type Engine

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

Engine runs the session loop against a Terminal.

func NewEngine

func NewEngine(exp *installation.Installation, applier *Applier) *Engine

NewEngine creates a runtime engine.

func (*Engine) Applier

func (e *Engine) Applier() *Applier

Applier returns the identity/space applier.

func (*Engine) EnableRateLimit

func (e *Engine) EnableRateLimit(rate, burst float64)

EnableRateLimit enables per-session action throttling.

func (*Engine) HandleInput

func (e *Engine) HandleInput(sess *Session, input string) error

HandleInput resolves and runs an action for one input token.

func (*Engine) Installation

func (e *Engine) Installation() *installation.Installation

Installation returns the current definition.

func (*Engine) NewSessionID

func (e *Engine) NewSessionID() string

NewSessionID allocates a unique session id.

func (*Engine) NoteReloadFailure

func (e *Engine) NoteReloadFailure()

NoteReloadFailure increments reload failure metrics.

func (*Engine) RedrawSessions

func (e *Engine) RedrawSessions()

RedrawSessions paints the current scene for every session that has a terminal.

func (*Engine) RegisterSession

func (e *Engine) RegisterSession(sess *Session)

RegisterSession adds a session to the engine registry.

func (*Engine) ReloadFailures

func (e *Engine) ReloadFailures() uint64

ReloadFailures returns failed hot-reload attempts.

func (*Engine) Render

func (e *Engine) Render(sess *Session, term Terminal) error

Render writes the current scene to the terminal. A placed input is painted inside its rectangle. Otherwise the caller draws the prompt row.

func (*Engine) RenderText

func (e *Engine) RenderText(sess *Session) (string, error)

RenderText returns the current scene output without writing a terminal.

func (*Engine) RepaintScene added in v0.1.3

func (e *Engine) RepaintScene(scene components.SceneID) error

RepaintScene paints every registered session whose current scene is scene. It applies no effects. An unknown scene or a scene with no sessions is a no-op.

func (*Engine) RunLoop

func (e *Engine) RunLoop(sess *Session, term Terminal, activity chan<- struct{}) error

RunLoop drives read input → action → render until terminal closes. Input filtering layers are documented in terminalinput.go. activity, when non-nil, receives a signal on each non-empty input (for idle timeouts).

func (*Engine) Sessions

func (e *Engine) Sessions() []*Session

Sessions returns all live sessions.

func (*Engine) SetActionHooks

func (e *Engine) SetActionHooks(h ActionHooks)

SetActionHooks configures before/after action callbacks.

func (*Engine) SetInputPolicy

func (e *Engine) SetInputPolicy(scrollbackEcho bool, transcript TranscriptMode)

SetInputPolicy chooses prompt scrollback and the command transcript. Zero values match the defaults: a bare prompt, and a transcript cleared on scene change.

func (*Engine) SetInstallation

func (e *Engine) SetInstallation(exp *installation.Installation) error

SetInstallation hot-swaps the installation definition after validation.

func (*Engine) SetLogger

func (e *Engine) SetLogger(l *slog.Logger)

SetLogger enables structured logs for actions and render errors.

func (*Engine) SetOnAction

func (e *Engine) SetOnAction(fn func())

SetOnAction hooks action execution for metrics.

func (*Engine) SetTheme

func (e *Engine) SetTheme(t render.Theme)

SetTheme installs the theme RenderContext.Theme returns. Call it before sessions connect. An unset theme is render.Default.

func (*Engine) SpaceSnapshots

func (e *Engine) SpaceSnapshots() map[string]SpaceSnapshot

SpaceSnapshots returns read-only space summaries for inspection.

func (*Engine) Submit added in v0.1.2

func (e *Engine) Submit(sessID string, effects []components.Effect) error

Submit applies effects to one registered session and paints it. Space effects in the slice run once. Session effects run on that session. Unknown ids return an error. Hooks, the action rate limiter, and onAction are not used.

func (*Engine) SubmitAll added in v0.1.2

func (e *Engine) SubmitAll(effects []components.Effect) error

SubmitAll applies effects to every registered session. Space effects run once. Session effects run once per session. An empty registry applies nothing.

func (*Engine) SubmitToSpace added in v0.1.2

func (e *Engine) SubmitToSpace(space components.SpaceID, effects []components.Effect) error

SubmitToSpace applies effects to current members of space. Space effects run once. Session effects run once per member. An empty member list applies nothing.

func (*Engine) UnregisterSession

func (e *Engine) UnregisterSession(id string)

UnregisterSession removes a session.

func (*Engine) UpdateAssets

func (e *Engine) UpdateAssets(assets map[string]string) error

UpdateAssets replaces asset content on the live installation.

type InputPrompter

type InputPrompter interface {
	BeginInputLine() error
	CommitInputLine(line string) error
	RejectInput(msg string) error
}

InputPrompter is optional. SSHTerminal writes a command line after each scene frame. CommitInputLine reprints the submitted line and a fresh prompt on the next line. RejectInput reports a line the current scene does not accept, then reprints the prompt.

type KeyMode

type KeyMode interface {
	SetKeys(keys []string)
}

KeyMode is optional. A nil or empty key list is line entry. A non-empty list reads one matching key and does not wait for Enter.

type LineEditor

type LineEditor interface {
	SetRedraw(func())
	SetComplete(func(prefix string) string)
	RestoreInputLine()
}

LineEditor is optional. SSHTerminal edits the current line and restores it after a redraw.

type LineEndTracer

type LineEndTracer interface {
	LineEndReason() string
	SubmitCSI() string
	SkippedCSI() string
}

LineEndTracer is optional. SSHTerminal implements it for debug logs after ReadInput.

type SSHTerminal

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

SSHTerminal adapts a gliderlabs SSH session to Terminal.

func NewSSHTerminal

func NewSSHTerminal(sess ssh.Session) *SSHTerminal

NewSSHTerminal wraps an SSH session.

func (*SSHTerminal) BeginInputLine

func (t *SSHTerminal) BeginInputLine() error

BeginInputLine prints the command prompt on the line after a scene frame.

func (*SSHTerminal) ClearRecall

func (t *SSHTerminal) ClearRecall()

ClearRecall drops up/down lines. A scene change calls this so the next scene starts empty.

func (*SSHTerminal) Close

func (t *SSHTerminal) Close() error

func (*SSHTerminal) CommitInputLine

func (t *SSHTerminal) CommitInputLine(line string) error

CommitInputLine keeps the submitted command and moves ">" onto the next line.

func (*SSHTerminal) LineEndReason

func (t *SSHTerminal) LineEndReason() string

func (*SSHTerminal) OnResize

func (t *SSHTerminal) OnResize(fn func(int, int))

func (*SSHTerminal) PaintSlot

func (t *SSHTerminal) PaintSlot()

PaintSlot redraws the caret rectangle from the line buffer.

func (*SSHTerminal) ReadInput

func (t *SSHTerminal) ReadInput() (string, error)

func (*SSHTerminal) RejectInput

func (t *SSHTerminal) RejectInput(msg string) error

RejectInput prints why a line was not run, then a new prompt.

func (*SSHTerminal) RejectSlot

func (t *SSHTerminal) RejectSlot(msg string)

RejectSlot shows msg inside the caret rectangle until the next edit.

func (*SSHTerminal) RestoreInputLine

func (t *SSHTerminal) RestoreInputLine()

RestoreInputLine reprints the prompt and any half-typed line. A key scene has no prompt, so a resize only keeps the scene that was just drawn.

func (*SSHTerminal) SetComplete

func (t *SSHTerminal) SetComplete(fn func(string) string)

SetComplete installs scene-key completion used by Tab.

func (*SSHTerminal) SetKeys

func (t *SSHTerminal) SetKeys(keys []string)

SetKeys selects single-key reads. An empty list returns to line entry.

func (*SSHTerminal) SetRedraw

func (t *SSHTerminal) SetRedraw(fn func())

SetRedraw installs the scene repaint used by Ctrl-L.

func (*SSHTerminal) SetSlot

func (t *SSHTerminal) SetSlot(in *render.Input)

SetSlot installs the caret rectangle. Nil restores the prompt row under the frame.

func (*SSHTerminal) SkippedCSI

func (t *SSHTerminal) SkippedCSI() string

func (*SSHTerminal) SlotActive

func (t *SSHTerminal) SlotActive() bool

SlotActive reports whether a caret rectangle is installed.

func (*SSHTerminal) SubmitCSI

func (t *SSHTerminal) SubmitCSI() string

func (*SSHTerminal) WindowSize

func (t *SSHTerminal) WindowSize() (width, height int, ok bool)

WindowSize returns the PTY size reported at session start.

func (*SSHTerminal) WriteFrame

func (t *SSHTerminal) WriteFrame(text string) error

func (*SSHTerminal) WriteGrid

func (t *SSHTerminal) WriteGrid(text string) error

WriteGrid clears the screen and writes text without adding a trailing newline, so a full-height grid does not scroll before the caret is placed. ponytail: autowrap is off for the write. The bottom-right cell can still wrap on some terminals if the last row is exactly the width. Upgrade path is CUP for that cell.

type Server

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

Server serves an installation over SSH.

func NewServer

func NewServer(cfg ServerConfig, engine *Engine) (*Server, error)

NewServer creates an SSH server for the engine.

func (*Server) ActiveSessions

func (s *Server) ActiveSessions() int

ActiveSessions returns the number of tracked SSH sessions.

func (*Server) Draining

func (s *Server) Draining() bool

Draining reports whether the server is shutting down.

func (*Server) Engine

func (s *Server) Engine() *Engine

EngineRef returns the underlying engine.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context) error

ListenAndServe starts the SSH server and blocks until ctx is done or error.

func (*Server) ListenAndServeOn

func (s *Server) ListenAndServeOn(ctx context.Context, ln net.Listener) error

ListenAndServeOn serves on an existing listener (tests).

func (*Server) ReloadInstallation

func (s *Server) ReloadInstallation(b *installation.Builder) error

ReloadInstallation validates and swaps the installation.

type ServerConfig

type ServerConfig struct {
	Addr              string
	DataDir           string
	HostKeyPath       string
	IdleTimeout       time.Duration
	MaxConns          int
	MaxConnsPerIP     int
	Logger            *slog.Logger
	Accounts          *AccountConfig
	AllowKeys         []string
	DenyKeys          []string
	AllowAccounts     []string
	DenyAccounts      []string
	RequireAccount    bool
	ShutdownGrace     time.Duration
	KeepAliveInterval time.Duration
	KeepAliveCountMax int
}

ServerConfig configures the SSH server.

func DefaultConfig

func DefaultConfig() ServerConfig

DefaultConfig returns dev-friendly defaults.

type Session

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

Session is one SSH connection's runtime state.

func NewSessionForTest

func NewSessionForTest(id string, idn identity.Identity, root components.SceneID) *Session

NewSessionForTest exposes session construction for tests in other packages.

func (*Session) CurrentScene

func (s *Session) CurrentScene() components.SceneID

CurrentScene returns the active scene id.

func (*Session) ID

func (s *Session) ID() string

ID returns the session identifier.

func (*Session) Identity

func (s *Session) Identity() identity.Identity

Identity returns the visitor identity.

func (*Session) InSpace

func (s *Session) InSpace(space components.SpaceID) bool

InSpace reports membership.

func (*Session) LastRender

func (s *Session) LastRender() (text string, size int)

LastRender returns the most recent rendered frame and its byte size.

func (*Session) LocalCopy

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

LocalCopy returns a snapshot of session-local state.

func (*Session) RecentCommands

func (s *Session) RecentCommands(n int) []string

RecentCommands returns the last n successful lines, oldest first. n <= 0 returns the whole list. The caller may keep the slice.

func (*Session) SetIdentityForTest

func (s *Session) SetIdentityForTest(idn identity.Identity)

SetIdentityForTest updates identity in tests.

func (*Session) Spaces

func (s *Session) Spaces() []components.SpaceID

Spaces returns joined space ids.

type SpaceSnapshot

type SpaceSnapshot struct {
	MemberCount int      `json:"member_count"`
	Keys        []string `json:"keys"`
}

SpaceSnapshot is a read-only space summary for inspection.

type Terminal

type Terminal interface {
	WriteFrame(text string) error
	ReadInput() (string, error)
	OnResize(func(width, height int))
	Close() error
}

Terminal abstracts SSH or fake terminal I/O for the session loop.

type TranscriptMode

type TranscriptMode int

TranscriptMode controls RecentCommands across a scene change.

const (
	// TranscriptClear drops the list when the scene changes. Zero value.
	TranscriptClear TranscriptMode = iota
	// TranscriptKeep leaves the list in place, including the line that transitioned.
	TranscriptKeep
	// TranscriptOff does not record lines.
	TranscriptOff
)

Jump to

Keyboard shortcuts

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