execsess

package
v1.5.93 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 13 Imported by: 0 modules, 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

Overview

Package execsess manages shell sessions: OS processes that outlive a single tool call so their output can be polled and their process group controlled (interrupt / kill). It is a leaf package depending only on the standard library: internal/agenttool adapts sessions to the model tool surface (bash / write_stdin) and the cli layer owns lifecycle (kill-on-exit) without an import cycle.

A session is created by Manager.Start and lives until it exits, the manager prunes it under capacity pressure, or KillAll runs at shutdown. Output is streamed into a bounded head+tail buffer, so a chatty command can never grow a session without limit; a reader polls the retained window with ReadNew, which reports any dropped middle as a single "[truncated N bytes]" marker.

Index

Constants

View Source
const OutputCapBytes = 1 << 20

OutputCapBytes bounds the output retained per session (a head and tail window). Retained bytes can briefly reach 1.5x this budget because the tail is compacted at 2x its share; the bound is what matters, not the exact size.

Variables

This section is empty.

Functions

This section is empty.

Types

type Manager

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

Manager owns a set of sessions and assigns their ids.

func NewManager

func NewManager() *Manager

NewManager returns an empty manager.

func (*Manager) Get

func (m *Manager) Get(id string) (*Session, bool)

Get returns the session with the given id, or (nil, false).

func (*Manager) KillAll

func (m *Manager) KillAll()

KillAll terminates every session that is still running. It is the shutdown hook drivers call so long-running commands are not orphaned.

func (*Manager) List added in v1.5.49

func (m *Manager) List() []Snapshot

List returns snapshots of every tracked session, newest first. Callers use it to offer TTY takeover without learning about the manager's mutable map.

func (*Manager) Start

func (m *Manager) Start(req StartRequest) (*Session, error)

Start spawns req.Argv, registers the session under a fresh id, and returns it. When the manager is at capacity it evicts one session first, mirroring codex's unified-exec policy: the most recently used sessions are protected, then the least recently used exited session is dropped, and only if every unprotected session is still running is the least recently used live one terminated to make room.

type Session

type Session struct {
	// ID is the stable handle (e.g. "bash_2") callers address.
	ID string
	// Command is the original shell command line.
	Command string
	// StartedAt is when the session was registered.
	StartedAt time.Time
	// contains filtered or unexported fields
}

Session is one managed process: its identity, bounded output, and state. All fields are guarded by mu; the process's writers, readers, and controls may touch it concurrently.

func (*Session) Exited

func (s *Session) Exited() bool

Exited reports whether the process has finished.

func (*Session) Interrupt

func (s *Session) Interrupt()

Interrupt delivers Ctrl-C to the session: the first call sends SIGINT to the process group; a second escalates to Kill so a process that ignores SIGINT cannot pin the session forever.

func (*Session) IsTTY

func (s *Session) IsTTY() bool

IsTTY reports whether the session runs on a pseudo-terminal (its stdin is writable with arbitrary input).

func (*Session) Kill

func (s *Session) Kill()

Kill terminates the process group: SIGTERM, a short grace period, then SIGKILL. It blocks until the process has been reaped.

func (*Session) LastUsed

func (s *Session) LastUsed() time.Time

LastUsed reports when the session was last interacted with: its spawn or the latest poll / write / interrupt. Capacity eviction treats the most recently used sessions as the ones worth keeping.

func (*Session) PendingOutput

func (s *Session) PendingOutput() bool

PendingOutput reports whether unread output is buffered.

func (*Session) ReadNew

func (s *Session) ReadNew() string

ReadNew returns output produced since the previous ReadNew, inserting a "[truncated N bytes]" marker where the bounded buffer dropped a middle region. It advances the reader cursor.

func (*Session) Resize added in v1.5.49

func (s *Session) Resize(cols, rows int) error

Resize updates a live TTY session's window size. Pipe sessions reject it.

func (*Session) SendInput

func (s *Session) SendInput(text string) error

SendInput writes raw bytes to a tty session's stdin (for example a line of input, or a bare "\n" as an Enter keypress). It fails for pipe sessions and for sessions that have already exited. The echo of the input appears in the session output, exactly as it would on a terminal.

func (*Session) SetObserver

func (s *Session) SetObserver(fn func(string))

SetObserver replaces the output observer. Passing nil detaches it; an in-flight call for a chunk already being written may still complete.

func (*Session) Snapshot

func (s *Session) Snapshot() Snapshot

Snapshot returns a copy of the session's current state.

func (*Session) Subscribe added in v1.5.49

func (s *Session) Subscribe() (io.ReadWriteCloser, error)

Subscribe attaches a read/write connection to a TTY session without taking ownership of its process. Closing the connection detaches the view; it does not kill the command.

func (*Session) Wait

func (s *Session) Wait(ctx context.Context, d time.Duration, mode WaitMode) bool

Wait blocks until the process exits, the deadline elapses, or ctx is done. With WaitOutput it also returns once output newer than the reader's cursor arrived. It reports whether the process has exited.

func (*Session) Write

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

Write implements io.Writer: it appends one output chunk to the bounded buffer, forwards it to the observer (if any), and wakes waiting readers.

type SessionConnection added in v1.5.49

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

SessionConnection adapts one managed TTY to MyGo terminal's Conn contract. It mirrors retained output plus live chunks and writes keystrokes back to the same PTY. Close only detaches this reader.

func (*SessionConnection) Close added in v1.5.49

func (c *SessionConnection) Close() error

func (*SessionConnection) Read added in v1.5.49

func (c *SessionConnection) Read(p []byte) (int, error)

func (*SessionConnection) Resize added in v1.5.49

func (c *SessionConnection) Resize(cols, rows int) error

Resize is discovered by terminal.Options.Conn and forwarded to the PTY.

func (*SessionConnection) Write added in v1.5.49

func (c *SessionConnection) Write(p []byte) (int, error)

type Snapshot

type Snapshot struct {
	ID         string
	Command    string
	Status     Status
	ExitCode   int
	Err        string
	TimedOut   bool
	Timeout    time.Duration
	StartedAt  time.Time
	FinishedAt time.Time
}

Snapshot is a copy of a session's state at one instant.

type StartRequest

type StartRequest struct {
	// Command is the original shell command line, kept for display and for
	// callers that need to re-state what a session is running.
	Command string
	// Argv is the executable and its arguments to spawn (for the bash tool,
	// already wrapped for the platform shell and any sandbox runner).
	Argv []string
	// Dir is the working directory; empty uses the process CWD.
	Dir string
	// Prefix is the session id prefix; empty means "bash".
	Prefix string
	// Timeout, when positive, is a hard deadline: the session is killed when
	// it elapses and Snapshot reports TimedOut.
	Timeout time.Duration
	// Cleanup, when non-nil, runs once after the process exits (e.g. removing
	// a generated sandbox profile). It runs even when Start fails.
	Cleanup func()
	// Observer, when non-nil, receives each output chunk as it is written.
	// It is called from the writer goroutine without the session lock, so it
	// must be quick and must not call back into the session.
	Observer func(string)
	// TTY runs the command on a pseudo-terminal: stdin becomes writable with
	// arbitrary input, stdout/stderr are merged by the terminal, and a
	// conventional 24x80 window is reported. The default (false) is the pipe
	// session used for plain commands.
	TTY bool
	// Env holds extra "KEY=VALUE" entries merged into the process environment
	// (after the inherited one). TTY sessions add their own sanitation
	// entries; callers rarely set this directly.
	Env []string
}

StartRequest configures one session spawn.

type Status

type Status string

Status is a session's lifecycle state.

const (
	// StatusRunning means the process is still executing.
	StatusRunning Status = "running"
	// StatusExited means the process finished (successfully or not) or was
	// killed.
	StatusExited Status = "exited"
)

type WaitMode

type WaitMode int

WaitMode selects what a Wait call returns early for.

const (
	// WaitExit waits for the process to exit or the timeout/ctx to elapse.
	WaitExit WaitMode = iota
	// WaitOutput additionally returns when output newer than the reader's
	// cursor arrived.
	WaitOutput
)

Jump to

Keyboard shortcuts

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