session

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderSize     = 5
	MaxCmdLen      = 256
	MaxCwdLen      = 256
	MaxPayloadSize = 16 * 1024 * 1024 // 16 MB

	// InfoSize is the size of the IPC Info extern struct on 64-bit platforms.
	// Layout: clients_len(8) + pid(4) + cmd_len(2) + cwd_len(2) +
	//         cmd(256) + cwd(256) + created_at(8) + task_ended_at(8) +
	//         task_exit_code(1) + padding(7) = 552
	InfoSize = 552
)

Variables

View Source
var ErrSessionNotFound = errors.New("session not found")

Functions

func Attach

func Attach(cfg Config, name string) error

Attach connects to a session and relays I/O between the local terminal and the PTY.

func AttachSwitchSequence

func AttachSwitchSequence(target string) string

func ClaudeStatuslinePath added in v0.4.2

func ClaudeStatuslinePath(cfg Config, sessionName string) string

func CleanStaleSocket

func CleanStaleSocket(path string) error

CleanStaleSocket removes a socket file for a dead session and prunes session sidecars.

func Connect

func Connect(socketPath string) (net.Conn, error)

Connect dials a Unix domain socket with a timeout.

func DetachSession

func DetachSession(cfg Config, name string) error

DetachSession disconnects all attached clients from the named session without killing the daemon or shell process.

func FormatSessionName added in v0.6.4

func FormatSessionName(ctx GitContext) string

FormatSessionName returns a session name based on git context. For worktrees: "repo@branch". Otherwise: just the repo name.

func GitMetaPath added in v0.6.4

func GitMetaPath(cfg Config, sessionName string) string

GitMetaPath returns the path to the git metadata sidecar file for a session.

func IsSocket

func IsSocket(path string) bool

IsSocket returns true if the path is a Unix domain socket.

func KillSession

func KillSession(cfg Config, name string) error

KillSession sends a kill message to the named session.

func MarshalMessage

func MarshalMessage(tag Tag, payload []byte) []byte

MarshalMessage builds a complete wire message (header + payload). The returned slice is borrowed from a pool; callers that broadcast to multiple writers must call ReleaseMessage when done.

func ReleaseMessage added in v0.6.3

func ReleaseMessage(msg []byte)

ReleaseMessage returns a message buffer to the pool.

func RemoveDaemonBuildInfo added in v0.4.2

func RemoveDaemonBuildInfo(cfg Config, sessionName string) error

func RemoveSessionArtifacts added in v0.4.2

func RemoveSessionArtifacts(cfg Config, sessionName string) error

func RemoveSessionRuntimeFiles added in v0.4.2

func RemoveSessionRuntimeFiles(cfg Config, names ...string) error

func RenameSession

func RenameSession(cfg Config, oldName, newName string) error

RenameSession renames a session by renaming its socket file.

func RenameSessionArtifacts added in v0.4.2

func RenameSessionArtifacts(cfg Config, oldName, newName string) error

func RestoreBackendName

func RestoreBackendName() string

func SanitizeBranch added in v0.6.4

func SanitizeBranch(name string) string

SanitizeBranch replaces characters that are invalid in session names.

func SendMessage

func SendMessage(conn net.Conn, tag Tag, payload []byte) error

SendMessage writes a header + payload to a connection.

func SpawnDaemon

func SpawnDaemon(name string, shellCmd []string) error

SpawnDaemon starts a daemon in a new process (re-exec with --daemon flag).

func SpawnDaemonInDir added in v0.6.4

func SpawnDaemonInDir(name string, shellCmd []string, dir string) error

SpawnDaemonInDir spawns a new daemon process. If dir is non-empty, the daemon starts in that directory instead of the current working directory.

func StartDaemon

func StartDaemon(name string, shellCmd []string) error

StartDaemon creates a new session with a PTY and listens on a Unix socket. This is called in the re-exec'd daemon subprocess.

func ValidateSessionName added in v0.5.0

func ValidateSessionName(name string) error

ValidateSessionName checks that a session name is safe for use in file paths.

func WriteClaudeStatusline added in v0.4.2

func WriteClaudeStatusline(cfg Config, sessionName string, data []byte) error

func WriteGitMeta added in v0.6.4

func WriteGitMeta(cfg Config, sessionName string, ctx GitContext) error

WriteGitMeta atomically writes git context as a JSON sidecar file.

Types

type Config

type Config struct {
	SocketDir string
	LogDir    string
}

Config holds paths for session socket and log directories.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig resolves the socket directory:

  1. $TSM_DIR
  2. $XDG_RUNTIME_DIR/tsm
  3. $TMPDIR/tsm-{uid} (trailing slash stripped)
  4. /tmp/tsm-{uid}

func (Config) MaxSessionNameLen

func (c Config) MaxSessionNameLen() int

MaxSessionNameLen returns the maximum session name length based on the platform's sockaddr_un.sun_path limit minus the socket dir path.

func (Config) SocketPath

func (c Config) SocketPath(name string) string

SocketPath returns the full path to a session's Unix domain socket.

type Daemon

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

Daemon manages a single session: a PTY, a Unix socket, and connected clients.

type DaemonBuildInfo added in v0.4.2

type DaemonBuildInfo struct {
	Executable  string `json:"executable"`
	ModTimeUnix int64  `json:"mod_time_unix"`
}

func CurrentBuildInfo added in v0.4.2

func CurrentBuildInfo() (DaemonBuildInfo, error)

func ReadDaemonBuildInfo added in v0.4.2

func ReadDaemonBuildInfo(cfg Config, sessionName string) (DaemonBuildInfo, error)

type GitContext added in v0.6.4

type GitContext struct {
	RepoName   string `json:"repo_name"`   // basename of the main repo
	BranchName string `json:"branch_name"` // current branch or short SHA for detached HEAD
	IsWorktree bool   `json:"is_worktree"` // true if cwd is a linked worktree
	IsGitRepo  bool   `json:"is_git_repo"` // true if inside any git repo
	RepoRoot   string `json:"repo_root"`   // absolute path to main worktree root
	IsSplit    bool   `json:"is_split"`    // true if this is a workspace split pane session
}

GitContext holds git repository information detected from a working directory.

func DetectGitContext added in v0.6.4

func DetectGitContext(cwd string) GitContext

DetectGitContext detects git repository context from the given directory. It runs a single git rev-parse invocation and parses the output.

func ReadGitMeta added in v0.6.4

func ReadGitMeta(cfg Config, sessionName string) (GitContext, error)

ReadGitMeta reads git context from a JSON sidecar file.

type Header struct {
	Tag Tag
	Len uint32
}

Header is the 5-byte IPC message header: 1 byte tag + 4 byte LE payload length.

func ParseHeader

func ParseHeader(b []byte) (Header, error)

ParseHeader decodes a 5-byte buffer into a Header.

func (Header) Marshal

func (h Header) Marshal() [HeaderSize]byte

Marshal encodes the header into a 5-byte wire format.

type InfoPayload

type InfoPayload struct {
	ClientsLen   uint64
	PID          int32
	CmdLen       uint16
	CwdLen       uint16
	Cmd          [MaxCmdLen]byte
	Cwd          [MaxCwdLen]byte
	CreatedAt    uint64
	TaskEndedAt  uint64
	TaskExitCode uint8
}

InfoPayload represents the IPC Info extern struct (C ABI layout, 552 bytes).

func ParseInfo

func ParseInfo(data []byte) (InfoPayload, error)

ParseInfo decodes a 552-byte payload into an InfoPayload using exact C ABI offsets.

func ProbeSession

func ProbeSession(socketPath string) (*InfoPayload, error)

ProbeSession connects to a session socket and requests its info.

func (*InfoPayload) CmdString

func (info *InfoPayload) CmdString() string

CmdString returns the command as a Go string, clamped to MaxCmdLen.

func (*InfoPayload) CwdString

func (info *InfoPayload) CwdString() string

CwdString returns the working directory as a Go string, clamped to MaxCwdLen.

type PickerRequestError added in v0.6.4

type PickerRequestError struct{}

PickerRequestError is returned by Attach when the user requests the session picker.

func (*PickerRequestError) Error added in v0.6.4

func (e *PickerRequestError) Error() string

type Scrollback

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

Scrollback is a thread-safe ring buffer that stores raw PTY output.

func NewScrollback

func NewScrollback(size int) *Scrollback

NewScrollback creates a scrollback buffer with the given max byte capacity.

func (*Scrollback) Bytes

func (s *Scrollback) Bytes() []byte

Bytes returns the full contents of the ring buffer in order.

func (*Scrollback) TailLines

func (s *Scrollback) TailLines(n int) string

TailLines returns the last n lines from the buffer.

func (*Scrollback) Write

func (s *Scrollback) Write(p []byte) (int, error)

Write appends data to the ring buffer.

type Session

type Session struct {
	Name              string
	PID               string
	Clients           int
	StartedIn         string
	Cmd               string
	Memory            uint64 // filled later by process info
	Uptime            int    // filled later by process info
	AgentKind         string
	AgentState        string
	AgentSummary      string
	AgentUpdated      int64
	AgentModel        string
	AgentVersion      string
	AgentPrompt       string
	AgentPlan         string
	AgentApproval     string
	AgentSandbox      string
	AgentBranch       string
	AgentGitSHA       string
	AgentGitOrigin    string
	AgentName         string
	AgentRole         string
	AgentMemory       string
	AgentSessionID    string
	AgentSubagent     bool
	AgentInput        int64
	AgentOutput       int64
	AgentCached       int64
	AgentTotal        int64
	AgentContext      int64
	AgentCostUSD      float64
	AgentDurationMS   int64
	AgentAPIMS        int64
	AgentLinesAdded   int64
	AgentLinesRemoved int64
	AgentOutputStyle  string
	AgentProjectDir   string
	AgentWorktreePath string
	GitRepoName       string
	GitBranchName     string
	GitIsWorktree     bool
	GitRepoRoot       string
	GitIsSplit        bool
	CreatedAt         uint64
	TaskEndedAt       uint64
	TaskExitCode      uint8
}

Session represents a running session, compatible with the TUI's Session type.

func ListSessions

func ListSessions(cfg Config) ([]Session, error)

ListSessions discovers sessions by probing socket files in the socket directory.

func (Session) DisplayDir

func (s Session) DisplayDir() string

DisplayDir returns StartedIn with $HOME replaced by ~.

type SessionArtifact added in v0.4.2

type SessionArtifact struct {
	Session string
	Kind    string
	Path    string
}

func ListSessionArtifacts added in v0.4.2

func ListSessionArtifacts(cfg Config) ([]SessionArtifact, error)

type SwitchSessionError

type SwitchSessionError struct {
	Target string
}

func (*SwitchSessionError) Error

func (e *SwitchSessionError) Error() string

type Tag

type Tag uint8

Tag identifies the type of an IPC message.

const (
	TagInput     Tag = 0
	TagOutput    Tag = 1
	TagResize    Tag = 2
	TagDetach    Tag = 3
	TagDetachAll Tag = 4
	TagKill      Tag = 5
	TagInfo      Tag = 6
	TagInit      Tag = 7
	TagHistory   Tag = 8
	TagRun       Tag = 9
	TagAck       Tag = 10
	TagRename    Tag = 11
)

func ReadMessage

func ReadMessage(conn net.Conn, timeout time.Duration) (Tag, []byte, error)

ReadMessage reads a header + payload from a connection. A zero timeout clears the deadline (blocking read).

func (Tag) String

func (t Tag) String() string

type TerminalBackend

type TerminalBackend interface {
	Consume(data []byte)
	Resize(rows, cols uint16) error
	Snapshot() []byte
	Preview() []byte
	Close() error
}

TerminalBackend tracks PTY output and can serialize enough terminal state to bring a newly attached client back into sync with the daemon.

func NewTerminalBackend

func NewTerminalBackend(rows, cols uint16) TerminalBackend

Jump to

Keyboard shortcuts

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