gosh

package module
v0.0.0-...-08d4b41 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: BSD-3-Clause Imports: 38 Imported by: 0

README

gosh - Go Runtime Shell

Go Reference Go Report Card License

Embedded shell for the Go runtime.

Status: Experimental

Overview

gosh is a runtime-aware shell embedded in a Go process. It exposes live Go runtime state (goroutines, stacks, memory, GC, metrics, profiles, traces) through a virtual filesystem and POSIX-like commands. It can run locally, be embedded in services, or be served over SSH.

Concept: /proc for goroutines inside your Go binary.

Highlights

  • Runtime-native introspection without external agents.
  • /proc-like virtual filesystem for runtime state.
  • POSIX pipelines and redirection via mvdan.cc/sh.
  • Embeddable in any Go program.
  • Extensible with custom structs and functions.

Demo

$ ssh 127.0.0.1 -p 2222

gosh> ls /proc
1
2
debug
goroutines
log
mem
metrics
pprof
stack
trace

# Summary of all goroutines

gosh> goroutines | head -n 5
ID	STATE	TOP
1	running	runtime.gopark
2	waiting	main.main
...

# Inspect a single goroutine

gosh> cat /proc/2/status
Goroutine:	2
State:	waiting
Top:	main.main
Frames:	...

# Capture a CPU profile (writes to virtual FS)

gosh> profile cpu 5 /cpu.pprof

Quick start

Requirements
  • Go 1.25.5 or newer
  • Unix-like systems recommended
Install
go get github.com/sleepymole/gosh@latest
Embed a shell
package main

import (
    "context"
    "log"
    "os"

    "github.com/sleepymole/gosh"
)

func main() {
    sh, err := gosh.New(gosh.Options{
        In:     os.Stdin,
        Out:    os.Stdout,
        Err:    os.Stderr,
        Prompt: "gosh> ",
    })
    if err != nil {
        log.Fatal(err)
    }
    if err := sh.Run(context.Background()); err != nil {
        log.Fatal(err)
    }
}
Execute a single command
sh, _ := gosh.New(gosh.Options{Out: os.Stdout, Err: os.Stderr})
_ = sh.Exec(context.Background(), "goroutines | head -n 5")
Serve over SSH
ctx := context.Background()
err := gosh.ServeSSH(ctx, gosh.Options{}, gosh.SSHOptions{
    Addr: "127.0.0.1:2222",
    // Provide auth before binding to non-loopback addresses.
})

Core model

  • Virtual filesystem backed by memory and scoped to the Go process.
  • /proc-like layout that mirrors runtime state.
  • Text-first built-ins designed for pipelines.

Proc layout

  • /proc/<id> (dir): goroutine entry with stack and status.
  • /proc/<id>/stack: stack dump for a goroutine.
  • /proc/<id>/status: summary fields for a goroutine.
  • /proc/goroutines: tabular goroutine summary.
  • /proc/stack: full goroutine dump.
  • /proc/mem: memory and GC stats.
  • /proc/metrics: runtime metrics.
  • /proc/metrics/<prefix>: filtered metrics.
  • /proc/log/level: read/write log level string.
  • /proc/debug/memory: write free or gc (dangerous).
  • /proc/pprof/heap: heap profile.
  • /proc/pprof/profile?seconds=10: CPU profile.
  • /proc/trace?seconds=5: runtime trace (dangerous).
  • /proc/gc: trigger GC (dangerous).

Commands

POSIX-like built-ins

help, version, clear, pwd, cd, ls, stat, cat, head, tail, grep, wc, echo, printf, tee, touch, mkdir, rmdir, rm, cp, mv, mount, umount, quit, exit.

Runtime helpers

goroutines (alias ps), stack, mem, metrics, profile, trace, gc, call.

Scripts

Scripts live in the virtual filesystem and are discovered via PATH (default /bin). Files are executable if they have any exec bit or a shebang line.

Gosh scripts
  • #!/bin/gosh or .gosh extension (also accepts #!/usr/bin/env gosh).
  • Executed by the embedded POSIX interpreter.
Go scripts
  • #!/bin/gosh-go or .go extension (also accepts #!/usr/bin/env gosh-go).
  • Executed with Yaegi.
  • Safe mode uses a restricted stdlib allowlist (see yaegi_filter.go).
  • EnableDangerous enables the full Yaegi stdlib, including OS and network.

Go scripts can import gosh to interact with the shell:

  • Args() []string: command arguments.
  • Stdin(), Stdout(), Stderr(): streaming I/O.
  • Cwd(): current working directory.
  • ReadFile, WriteFile: access the virtual filesystem.
  • Builtin(name, args...): invoke built-in commands.
  • Call(name, payload): invoke registered Go functions (JSON in, JSON out).
  • Fatal(err): stop the script with an error.

Extensibility

Expose Go functions
sh, _ := gosh.New(gosh.Options{
    Funcs: map[string]gosh.Func{
        "reload": func(ctx context.Context, input []byte) (any, error) {
            return map[string]any{"ok": true}, nil
        },
    },
})

Call it from the shell:

gosh> call reload {}
Expose struct state as files (StructFS)
type Config struct {
    Enabled bool
    Name    string `gosh:"name"`
}

func (c *Config) Reload() error {
    return nil
}

sh, _ := gosh.New(gosh.Options{})
_ = sh.FS().Expose("/proc/app", &Config{})
  • Fields are readable and writable files.
  • Nested structs become subdirectories.
  • Methods become write-only files; writing triggers the call.
  • StructFS does not provide locking; coordinate concurrent access in the host.

Host mounts

Mount a host directory into the virtual filesystem (dangerous mode):

mount -t host /var/log /mnt/log
mount -t host -o ro /etc /mnt/etc
umount /mnt/log

Safety

  • EnableDangerous gates actions like trace, gc, and host mounts.
  • Safe mode restricts Go scripts to a limited stdlib allowlist.
  • SSH refuses non-loopback binds without authentication configured.

Compatibility notes

gosh favors a small, predictable subset of POSIX-style commands over full GNU coreutils compatibility. Most commands implement only a handful of flags, and unsupported options return an error. Use -- to pass arguments that begin with - as positional paths or patterns.

Supported flags today:

  • ls: -l, --color=always|auto|never, --no-color
  • head/tail: -n N

Roadmap

  • Improve autocomplete and interactive UX.
  • Expand runtime metrics and profiling surfaces.
  • Add more built-in scripts for common diagnostics.
  • Document and test Windows support explicitly.

Contributing

Contributions are welcome. Please open an issue or submit a PR.

License

This project is licensed under the BSD-3-Clause License.

  • github.com/google/gops: CLI and agent for Go process diagnostics.
  • net/http/pprof, runtime/pprof: profiling endpoints and data sources.
  • runtime/trace, go tool trace: scheduler and trace events.
  • github.com/arl/statsviz: browser UI for runtime metrics and profiles.
  • github.com/go-delve/delve: full debugger for Go.
  • github.com/traefik/yaegi, github.com/x-motemen/gore: Go interpreters.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExitShell = errors.New("exit shell")

ErrExitShell signals that the shell should stop.

View Source
var ErrInterrupted = errors.New("line reader interrupted")

ErrInterrupted signals an interrupted interactive read (for example, Ctrl-C).

Functions

func ServeSSH

func ServeSSH(ctx context.Context, opts Options, sshOpts SSHOptions) error

ServeSSH starts an embedded SSH server that serves shell sessions.

Types

type Command

type Command struct {
	Name    string
	Aliases []string
	Usage   string
	Run     func(ctx context.Context, sh *Shell, args []string, stdin io.Reader, stdout, stderr io.Writer) error
}

Command describes a shell command.

func DefaultCommands

func DefaultCommands() []Command

DefaultCommands returns the built-in command set.

type CompletionContext

type CompletionContext struct {
	Tokens     []string
	Prefix     string
	Command    string
	ArgIndex   int
	AfterRedir bool
	InToken    bool
}

type CompletionEngine

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

func (*CompletionEngine) Do

func (e *CompletionEngine) Do(line []rune, pos int) ([][]rune, int)

type CompletionProvider

type CompletionProvider interface {
	Complete(ctx CompletionContext, sh *Shell) []string
}

type Func

type Func func(ctx context.Context, input []byte) (any, error)

Func is a registered Go function that can be invoked by the shell. The input is a JSON payload, and the returned value is rendered as JSON.

type GoroutineInfo

type GoroutineInfo struct {
	ID    int    `json:"id"`
	State string `json:"state"`
	Top   string `json:"top"`
}

GoroutineInfo describes a goroutine summary.

type MemFS

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

MemFS is a simple in-memory filesystem with optional proc-like pseudo files.

func NewMemFS

func NewMemFS(proc *ProcFS) *MemFS

NewMemFS creates a MemFS with an attached ProcFS.

func (*MemFS) Chmod

func (m *MemFS) Chmod(p string, mode fs.FileMode) error

Chmod updates file permissions.

func (*MemFS) Copy

func (m *MemFS) Copy(src, dst string) error

Copy copies a file.

func (*MemFS) Expose

func (m *MemFS) Expose(procPath string, target any) error

Expose mounts a struct under /proc.

func (*MemFS) List

func (m *MemFS) List(p string) ([]fs.FileInfo, error)

List lists entries for a directory.

func (*MemFS) Mkdir

func (m *MemFS) Mkdir(p string) error

Mkdir creates a directory.

func (*MemFS) MountHost

func (m *MemFS) MountHost(mountPath, hostPath string, readOnly bool) error

MountHost mounts a host directory into the virtual filesystem.

func (*MemFS) Mounts

func (m *MemFS) Mounts() []MountInfo

Mounts returns the list of active mounts.

func (*MemFS) OpenReader

func (m *MemFS) OpenReader(p string) (io.ReadCloser, error)

OpenReader returns a reader for a file path.

func (*MemFS) OpenReaderContext

func (m *MemFS) OpenReaderContext(ctx context.Context, p string) (io.ReadCloser, error)

OpenReaderContext returns a reader for a file path with context support.

func (*MemFS) OpenWriter

func (m *MemFS) OpenWriter(p string, appendData bool) (io.WriteCloser, error)

OpenWriter returns a writer that writes to a file path.

func (*MemFS) ReadFile

func (m *MemFS) ReadFile(p string) ([]byte, error)

ReadFile reads the file contents.

func (*MemFS) ReadFileContext

func (m *MemFS) ReadFileContext(ctx context.Context, p string) ([]byte, error)

ReadFileContext reads file contents, honoring context when supported.

func (*MemFS) Remove

func (m *MemFS) Remove(p string) error

Remove deletes a file.

func (*MemFS) RemoveDir

func (m *MemFS) RemoveDir(p string) error

RemoveDir deletes an empty directory.

func (*MemFS) Rename

func (m *MemFS) Rename(oldPath, newPath string) error

Rename renames or moves a file or directory.

func (*MemFS) SetMaxBytes

func (m *MemFS) SetMaxBytes(max int64)

SetMaxBytes limits the total size of files in the filesystem.

func (*MemFS) Stat

func (m *MemFS) Stat(p string) (fs.FileInfo, error)

Stat returns metadata for a path.

func (*MemFS) Touch

func (m *MemFS) Touch(p string) error

Touch creates or updates a file mtime.

func (*MemFS) Unexpose

func (m *MemFS) Unexpose(procPath string) error

Unexpose removes a struct mount under /proc.

func (*MemFS) Unmount

func (m *MemFS) Unmount(mountPath string) error

Unmount removes a mounted host directory.

func (*MemFS) WriteFile

func (m *MemFS) WriteFile(p string, data []byte, appendData bool) error

WriteFile writes data to a file, creating it if needed.

type MemReport

type MemReport struct {
	Mem runtime.MemStats `json:"mem"`
	GC  debug.GCStats    `json:"gc"`
}

MemReport captures a memory snapshot for JSON output.

type MetricSample

type MetricSample struct {
	Name  string `json:"name"`
	Value any    `json:"value"`
	Unit  string `json:"unit"`
}

MetricSample describes a runtime metric sample.

type MountInfo

type MountInfo struct {
	Path     string
	Target   string
	ReadOnly bool
}

MountInfo describes a host mount point.

type Options

type Options struct {
	In              io.Reader
	Out             io.Writer
	Err             io.Writer
	Prompt          string
	Version         string
	EnableDangerous bool
	FS              *MemFS
	Funcs           map[string]Func
	Commands        []Command
	Vars            map[string]string
	ScriptBindings  map[string]map[string]any
}

Options configures a Shell.

type ProcFS

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

ProcFS exposes Go runtime data as pseudo files.

func NewProcFS

func NewProcFS(enableDangerous bool) *ProcFS

NewProcFS creates a ProcFS instance.

func (*ProcFS) Expose

func (p *ProcFS) Expose(procPath string, target any) error

Expose mounts a struct under /proc for inspection and updates.

func (*ProcFS) List

func (p *ProcFS) List(path string) ([]fs.FileInfo, error)

List lists a proc directory.

func (*ProcFS) LogLevel

func (p *ProcFS) LogLevel() string

LogLevel returns the current log level.

func (*ProcFS) OpenReaderContext

func (p *ProcFS) OpenReaderContext(ctx context.Context, path string) (io.ReadCloser, error)

OpenReaderContext opens a streaming reader for a proc path.

func (*ProcFS) Read

func (p *ProcFS) Read(path string) ([]byte, error)

Read reads a proc path.

func (*ProcFS) ReadContext

func (p *ProcFS) ReadContext(ctx context.Context, path string) ([]byte, error)

ReadContext reads a proc path with context-aware operations.

func (*ProcFS) Stat

func (p *ProcFS) Stat(path string) (fs.FileInfo, error)

Stat returns metadata for a proc path.

func (*ProcFS) Unexpose

func (p *ProcFS) Unexpose(procPath string) error

Unexpose removes a struct mount under /proc.

func (*ProcFS) Write

func (p *ProcFS) Write(path string, data []byte) error

Write writes to a proc path.

type SSHOptions

type SSHOptions struct {
	Addr           string
	HostKeySigner  ssh.Signer
	AuthorizedKeys []ssh.PublicKey
	PasswordAuth   func(ctx context.Context, user, pass string) bool
	AllowPTY       bool
}

SSHOptions configures the embedded SSH server.

type Shell

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

Shell is an embedded runtime-aware shell.

func New

func New(opts Options) (*Shell, error)

New creates a Shell with the provided options.

func (*Shell) Commands

func (s *Shell) Commands() []Command

func (*Shell) Cwd

func (s *Shell) Cwd() string

func (*Shell) EnableDangerous

func (s *Shell) EnableDangerous() bool

func (*Shell) Exec

func (s *Shell) Exec(ctx context.Context, line string) error

Exec executes a single command line.

func (*Shell) FS

func (s *Shell) FS() *MemFS

func (*Shell) Func

func (s *Shell) Func(name string) (Func, bool)

func (*Shell) Run

func (s *Shell) Run(ctx context.Context) error

Run starts the interactive shell loop.

func (*Shell) Version

func (s *Shell) Version() string

type StructFS

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

StructFS exposes a struct's fields and methods as files.

func NewStructFS

func NewStructFS(target any) (*StructFS, error)

NewStructFS creates a StructFS for a pointer to a struct.

func (*StructFS) List

func (s *StructFS) List(relPath string) ([]fs.FileInfo, error)

List lists entries under a struct directory.

func (*StructFS) OpenReaderContext

func (s *StructFS) OpenReaderContext(_ context.Context, relPath string) (io.ReadCloser, error)

OpenReaderContext opens a reader for a struct path.

func (*StructFS) Read

func (s *StructFS) Read(relPath string) ([]byte, error)

Read returns the contents of a field path.

func (*StructFS) Stat

func (s *StructFS) Stat(relPath string) (fs.FileInfo, error)

Stat returns file info for a path inside the struct.

func (*StructFS) Write

func (s *StructFS) Write(relPath string, data []byte) error

Write writes to a field or invokes a method path.

Directories

Path Synopsis
cmd
gosh command

Jump to

Keyboard shortcuts

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