Documentation
¶
Overview ¶
Package webserver provides a web-based terminal interface for pi-go. It exposes the pi-go agent via a browser with xterm.js, authenticated through a pairing code flow. It exposes the pi-go agent via a browser with xterm.js, authenticated through a pairing code flow.
Index ¶
- Constants
- Variables
- func KeyNames() []string
- func ValidateCode(code string) bool
- type ApprovedPair
- type Config
- type PairResponse
- type PairStatus
- type PairingManager
- func (pm *PairingManager) Approve(code string) (string, error)
- func (pm *PairingManager) CheckStatus(token string) (PairStatus, error)
- func (pm *PairingManager) CleanupExpired()
- func (pm *PairingManager) CreatePair(project string) (code, token string, err error)
- func (pm *PairingManager) CreatePairWithContext(project string) (code, token string, err error)
- func (pm *PairingManager) GetProject(token string) (string, error)
- func (pm *PairingManager) IsApproved(token string) bool
- func (pm *PairingManager) LockedOut() <-chan struct{}
- type PendingPair
- type PtyBridge
- func (pb *PtyBridge) Alive() bool
- func (pb *PtyBridge) AttachWebSocket(conn *websocket.Conn, sessionID string)
- func (pb *PtyBridge) Close() error
- func (pb *PtyBridge) HandleWebSocket(conn *websocket.Conn, sessionID string)
- func (pb *PtyBridge) LastOutput() time.Time
- func (pb *PtyBridge) Resize(cols, rows int) bool
- func (pb *PtyBridge) Screen(n int) string
- func (pb *PtyBridge) SendKey(name string) error
- func (pb *PtyBridge) SendPrompt(text string) error
- func (pb *PtyBridge) Start() error
- func (pb *PtyBridge) WaitForIdle(ctx context.Context, quiet, timeout time.Duration) bool
- type PtyPool
- type Server
- type ServerV2
- func (s *ServerV2) Addr() string
- func (s *ServerV2) BootstrapPair(project string) (string, string, error)
- func (s *ServerV2) EnableVoice(ctx context.Context, apiKey string, opts ...voicegemini.Option) error
- func (s *ServerV2) LockedOut() <-chan struct{}
- func (s *ServerV2) PairingManager() *PairingManager
- func (s *ServerV2) SessionManager() *SessionManager
- func (s *ServerV2) Shutdown(ctx context.Context) error
- func (s *ServerV2) Start() error
- type SessionManager
- func (sm *SessionManager) CleanupExpired()
- func (sm *SessionManager) Close()
- func (sm *SessionManager) CloseSession(sessionID string) error
- func (sm *SessionManager) CreateSession(project, token string) (*WebSession, error)
- func (sm *SessionManager) GetSession(sessionID string) (*WebSession, bool)
- func (sm *SessionManager) SessionCount() int
- type StatusResponse
- type WSMessage
- type WebSession
- type WebSocketHandler
Constants ¶
const DefaultAddr = "127.0.0.1:8765"
DefaultAddr is the listen address used when Config.Addr is empty. It binds loopback only: this server hands whoever pairs with it a terminal running the agent, so exposing it to the network is a decision an operator makes explicitly with --addr (e.g. --addr 0.0.0.0:8765), never a default. 8765 is picked to stay clear of the 8080/3000 range every other local dev server squats on, so `pi serve` does not collide with whatever the project itself is running.
Variables ¶
var ErrTooManyAttempts = errors.New("too many pairing attempts")
ErrTooManyAttempts is returned by Approve once the failure budget is spent. It is distinct from a plain wrong-code error so callers and tests can tell a terminal refusal from an ordinary rejection.
Functions ¶
func KeyNames ¶ added in v0.0.75
func KeyNames() []string
KeyNames lists the keys SendKey accepts, for the tool description and for the error a bad name gets back.
func ValidateCode ¶
ValidateCode checks if a code is valid (6 digits).
Types ¶
type ApprovedPair ¶
ApprovedPair represents an approved pairing token.
type Config ¶
type Config struct {
Addr string
PairingTimeout time.Duration
StaticDir string
Project string
Model string
BaseURL string
Headers []string
Insecure bool
Logger *slog.Logger // if nil, a no-op logger is used
}
Config holds server configuration.
type PairResponse ¶
type PairResponse struct {
Code string `json:"code"`
}
PairResponse is the JSON body returned by the pairing endpoints. It deliberately carries no token: /api/pair answers unauthenticated callers, so anything in here is public. The token stays server-side and reaches the operator out-of-band (the startup banner) and the browser as the pi_token cookie set once a code is submitted. The internal view that does carry the token is ServerV2.activePair.
type PairStatus ¶
type PairStatus string
PairStatus represents the status of a pairing request.
const ( PairStatusPending PairStatus = "pending" PairStatusApproved PairStatus = "approved" PairStatusExpired PairStatus = "expired" PairStatusUnknown PairStatus = "unknown" )
type PairingManager ¶
type PairingManager struct {
// contains filtered or unexported fields
}
PairingManager handles pairing code generation, approval, and expiry.
func NewPairingManager ¶
func NewPairingManager(timeout time.Duration) *PairingManager
NewPairingManager creates a new PairingManager with the specified timeout.
func (*PairingManager) Approve ¶
func (pm *PairingManager) Approve(code string) (string, error)
Approve approves a pairing code and returns the associated token. Failed attempts are counted: once the budget is spent every pending pair is invalidated and every later attempt is refused, including a correct code.
func (*PairingManager) CheckStatus ¶
func (pm *PairingManager) CheckStatus(token string) (PairStatus, error)
CheckStatus returns the current status of a pairing token.
func (*PairingManager) CleanupExpired ¶
func (pm *PairingManager) CleanupExpired()
CleanupExpired removes expired pending codes.
func (*PairingManager) CreatePair ¶
func (pm *PairingManager) CreatePair(project string) (code, token string, err error)
CreatePair generates a new 6-digit pairing code and returns the code, token.
func (*PairingManager) CreatePairWithContext ¶
func (pm *PairingManager) CreatePairWithContext(project string) (code, token string, err error)
CreatePairWithContext generates a pair. The context parameters the QR payload once needed are gone with it; the signature is kept so callers read the same.
func (*PairingManager) GetProject ¶
func (pm *PairingManager) GetProject(token string) (string, error)
GetProject returns the project path for an approved token.
func (*PairingManager) IsApproved ¶
func (pm *PairingManager) IsApproved(token string) bool
IsApproved checks if a token has been approved.
func (*PairingManager) LockedOut ¶ added in v0.0.83
func (pm *PairingManager) LockedOut() <-chan struct{}
LockedOut returns a channel closed once pairing has spent its failure budget. The server selects on it to shut down, which is what makes three attempts a hard stop rather than a pause an attacker can wait out.
type PendingPair ¶
type PendingPair struct {
Code string
CreatedAt time.Time
ExpiresAt time.Time
Project string
Token string // browser token to approve
}
PendingPair represents a pending pairing request.
type PtyBridge ¶
type PtyBridge struct {
// contains filtered or unexported fields
}
PtyBridge manages a long-lived PTY process that survives WebSocket reconnects.
func NewPtyBridge ¶
func NewPtyBridge(project, model, baseURL string, headers []string, insecure bool, logger *slog.Logger) *PtyBridge
NewPtyBridge creates a new PTY bridge for the given project, model, base URL, optional extra HTTP headers (key=value), and insecure TLS toggle. All of these are forwarded to the spawned pi subprocess via command-line flags.
func (*PtyBridge) AttachWebSocket ¶
AttachWebSocket connects a WebSocket to this PTY bridge. Blocks until the WebSocket disconnects or the PTY process exits. After return the PTY is still alive; call Close() to kill it.
func (*PtyBridge) HandleWebSocket ¶
HandleWebSocket is a convenience wrapper: Start + AttachWebSocket + Close. Used when session persistence is not needed.
func (*PtyBridge) LastOutput ¶ added in v0.0.75
LastOutput reports when the PTY last produced bytes. Zero means it has not produced any since this bridge started.
func (*PtyBridge) Resize ¶ added in v0.0.24
Resize updates the PTY size, clamping out-of-range geometry. No-op when running in pipe fallback mode or when the size is unchanged. Reports whether a new size reached the PTY.
func (*PtyBridge) Screen ¶ added in v0.0.75
Screen returns the last n lines of what the pi session has drawn, as plain text.
The capture is filled by the PTY→WebSocket pump, so it holds what the browser was shown. With no browser attached nothing drains the PTY at all, and this returns the screen as of the last attachment — which is the honest answer, since the terminal genuinely has not advanced.
func (*PtyBridge) SendKey ¶ added in v0.0.75
SendKey sends one named key. This is what answers a permission prompt or interrupts a run — the moments where a voice user needs a keystroke, not a sentence.
func (*PtyBridge) SendPrompt ¶ added in v0.0.75
SendPrompt types text into the pi session and submits it, exactly as if the user had typed it in the browser terminal.
Control characters are stripped rather than escaped: the argument comes from a speech transcript by way of a language model, and the one thing it must not be able to do is smuggle an escape sequence or a stray carriage return that submits half a sentence.
func (*PtyBridge) Start ¶
Start launches the PTY child process. Must be called before AttachWebSocket.
func (*PtyBridge) WaitForIdle ¶ added in v0.0.75
WaitForIdle blocks until the pi session has produced no output for quiet, or until timeout elapses or ctx is done. It reports whether the session actually went quiet.
This is what turns "start the agent and hope" into a conversation: the voice model calls it after sending a prompt and only speaks once the agent has stopped writing, instead of narrating a half-rendered frame.
ctx is the relay's: a browser that closes mid-wait must not leave this polling for the rest of the timeout on behalf of a conversation that has already ended.
type PtyPool ¶
type PtyPool struct {
// contains filtered or unexported fields
}
PtyPool manages PTY bridges keyed by session ID.
func (*PtyPool) CloseAll ¶
func (p *PtyPool) CloseAll()
CloseAll terminates all PTY bridges in the pool.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server holds HTTP handlers and dependencies.
func (*Server) GetProject ¶
GetProject returns the project for a given token.
func (*Server) PairingManager ¶
func (s *Server) PairingManager() *PairingManager
PairingManager returns the pairing manager.
type ServerV2 ¶
type ServerV2 struct {
// contains filtered or unexported fields
}
ServerV2 is the main web server.
func NewServerV2 ¶
NewServerV2 creates a new server with the given configuration.
func (*ServerV2) Addr ¶
Addr returns the actual listen address (reflects the bound port when using :0).
func (*ServerV2) BootstrapPair ¶
BootstrapPair creates (or reuses) an active pair for CLI-first flow.
func (*ServerV2) EnableVoice ¶ added in v0.0.75
func (s *ServerV2) EnableVoice(ctx context.Context, apiKey string, opts ...voicegemini.Option) error
EnableVoice configures the Gemini Live transport and verifies the key and model before the first microphone byte.
Verification is deliberately at enable time rather than at first dial: a wrong key or a non-Live model is a boot error the operator sees in the terminal, not a dead microphone the user discovers mid-sentence.
func (*ServerV2) LockedOut ¶ added in v0.0.83
func (s *ServerV2) LockedOut() <-chan struct{}
LockedOut returns a channel closed once pairing has spent its failure budget.
Serve selects on it alongside the interrupt signal: three wrong codes stop the server rather than opening a window an attacker can wait out.
func (*ServerV2) PairingManager ¶
func (s *ServerV2) PairingManager() *PairingManager
PairingManager returns the pairing manager.
func (*ServerV2) SessionManager ¶
func (s *ServerV2) SessionManager() *SessionManager
SessionManager returns the session manager.
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages per-tab sessions.
func NewSessionManager ¶
func NewSessionManager() *SessionManager
NewSessionManager creates a new session manager.
func (*SessionManager) CleanupExpired ¶
func (sm *SessionManager) CleanupExpired()
CleanupExpired removes expired sessions. Deprecated: Use cleanupLoop instead.
func (*SessionManager) Close ¶
func (sm *SessionManager) Close()
Close stops the session manager and cleans up.
func (*SessionManager) CloseSession ¶
func (sm *SessionManager) CloseSession(sessionID string) error
CloseSession marks a session as closed.
func (*SessionManager) CreateSession ¶
func (sm *SessionManager) CreateSession(project, token string) (*WebSession, error)
CreateSession creates a new session for a browser tab.
func (*SessionManager) GetSession ¶
func (sm *SessionManager) GetSession(sessionID string) (*WebSession, bool)
GetSession retrieves a session by ID.
func (*SessionManager) SessionCount ¶
func (sm *SessionManager) SessionCount() int
SessionCount returns the number of active sessions.
type StatusResponse ¶
type StatusResponse struct {
Status PairStatus `json:"status"`
SessionID string `json:"sessionID,omitempty"`
}
StatusResponse represents the API response for status check.
type WebSession ¶
type WebSession struct {
ID string
Project string
Token string
CreatedAt time.Time
ClosedAt time.Time
Closed bool
}
WebSession represents an isolated browser tab session.
type WebSocketHandler ¶
type WebSocketHandler struct {
// contains filtered or unexported fields
}
WebSocketHandler handles WebSocket connections for terminal.
func NewWebSocketHandler ¶
func NewWebSocketHandler(sessionManager *SessionManager) *WebSocketHandler
NewWebSocketHandler creates a new WebSocket handler.
func (*WebSocketHandler) HandleWebSocket ¶
func (wh *WebSocketHandler) HandleWebSocket(w http.ResponseWriter, r *http.Request)
HandleWebSocket handles a WebSocket connection.