Help us shape the future of Go! Take the 2026 Go Developer Survey

session

package
v0.69.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package session is the session service: create, recycle, rename, delete and prune sessions, and spawn their terminals.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RenderUserCommandWindows

func RenderUserCommandWindows(renderer *tmpl.Renderer, windows []config.WindowConfig, data map[string]any) ([]multiplexer.WindowSpec, error)

RenderUserCommandWindows renders windows from a UserCommand using the provided template data map. Unlike RenderWindows, it accepts map[string]any to include .Form and session variables.

func RenderWindows

func RenderWindows(renderer *tmpl.Renderer, windows []config.WindowConfig, data SpawnData) ([]multiplexer.WindowSpec, error)

RenderWindows renders a slice of WindowConfig templates against SpawnData, producing fully resolved window specifications for the multiplexer client.

func Target

func Target(sess session.Session) multiplexer.Target

SessionTarget resolves the actual multiplexer session name for a Hive session.

Types

type CreateOptions

type CreateOptions struct {
	Name       string // Session name (used in path)
	SessionID  string // Session ID (auto-generated if empty)
	Prompt     string // Prompt to pass to spawned terminal (batch only)
	Remote     string // Git remote URL to clone (auto-detected if empty)
	Source     string // Source directory for file copying
	Background bool   // Create session without attaching to tmux
	// CloneStrategy selects the clone method: "full" (default) or "worktree".
	// Empty resolves via config rule matching, then global config, then "full".
	CloneStrategy string
	// SkipSpawn skips the configured spawn strategy (windows:).
	// The caller is responsible for launching any terminal or tmux session. Use this
	// when the session directory is needed but terminal management happens elsewhere
	// (e.g. CreateSessionWithWindows, which creates the tmux session itself).
	SkipSpawn bool
	// AgentKey selects a named agent profile for this session's spawn command.
	// When non-empty, the spawn templates use that profile's command/flags instead
	// of the process-wide default. Must match a key in config.Agents.Profiles.
	AgentKey string
	// Tags are normalized with session.NormalizeTags; an invalid tag
	// fails the create.
	Tags []string
	// Env holds KEY=VALUE pairs for the session's tmux environment.
	Env []string
	// CollisionSuffix is appended to a Name whose slug is taken. Use an id that
	// is stable across retries, so a retry collides with its own earlier session.
	CollisionSuffix string
	// Progress receives human-readable progress lines during session creation.
	// When non-nil, service output (hooks, file copies) is also redirected here.
	Progress io.Writer
}

CreateOptions configures session creation.

type CreateSessionError

type CreateSessionError struct {
	Operation     string
	Destination   string
	CloneStrategy string
	Err           error
}

CreateSessionError describes a session creation step that failed after its destination was resolved.

func (*CreateSessionError) Error

func (e *CreateSessionError) Error() string

func (*CreateSessionError) Unwrap

func (e *CreateSessionError) Unwrap() error

type Detector

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

Detector finds the current session from the working directory.

func NewDetector

func NewDetector(store session.Store) *Detector

NewDetector creates a new session detector.

func (*Detector) DetectSession

func (d *Detector) DetectSession(ctx context.Context) (string, error)

DetectSession returns the session ID for the current working directory. Returns empty string if not in a hive session, or an error if detection fails.

func (*Detector) DetectSessionFromPath

func (d *Detector) DetectSessionFromPath(ctx context.Context, path string) (string, error)

DetectSessionFromPath returns the session ID for the given path. Returns empty string if the path is not within a hive session, or an error if detection fails.

func (*Detector) SessionAtPath

func (d *Detector) SessionAtPath(ctx context.Context, path string) (session.Session, bool, error)

SessionAtPath returns the active session whose checkout holds path, and false when path is inside none.

type FileCopier

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

FileCopier copies files from a source directory to a destination.

func NewFileCopier

func NewFileCopier(log zerolog.Logger, styler OutputStyler, stdout io.Writer) *FileCopier

NewFileCopier creates a new FileCopier.

func (*FileCopier) CopyFiles

func (c *FileCopier) CopyFiles(ctx context.Context, rule config.Rule, sourceDir, destDir string) error

CopyFiles copies files matching the rule's copy patterns from sourceDir to destDir.

type HookRunner

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

HookRunner executes repository-specific setup hooks.

func NewHookRunner

func NewHookRunner(log zerolog.Logger, executor executil.Executor, renderer *tmpl.Renderer, styler OutputStyler, stdout, stderr io.Writer) *HookRunner

NewHookRunner creates a new HookRunner.

func (*HookRunner) RunHooks

func (h *HookRunner) RunHooks(ctx context.Context, rule config.Rule, path string, data config.SpawnTemplateData) error

RunHooks executes the commands from a matched rule, rendering each as a Go template.

type LaunchError

type LaunchError struct {
	Name   string
	Remote string
	// Destination and CloneStrategy come off CreateSessionError. They are
	// empty for a failure raised before a checkout was resolved, or after the
	// clone (a spawn that failed).
	Destination   string
	CloneStrategy string
	// LeftoverCheckout reports that Destination is still on disk: git removes
	// its own directory when it refuses a clone, but keeps a complete one when
	// a post-checkout hook fails.
	LeftoverCheckout bool
	// Step is the failed operation ("clone repository", "worktree add") when
	// CreateSessionError carries one, and otherwise the last progress line.
	Step   string
	Output string
	Err    error
}

LaunchError is a failed CreateFromRequest, carrying what a caller needs to hand the request back as a retryable draft. Nothing should match on its text (ADR a-failed-session-creation-is-a-retryable-draft).

func (*LaunchError) Error

func (e *LaunchError) Error() string

func (*LaunchError) Unwrap

func (e *LaunchError) Unwrap() error

type LaunchOptions

type LaunchOptions struct {
	Repositories      []LaunchRepository
	DefaultRepository string
	Agents            []string
	DefaultAgent      string
}

LaunchOptions supplies the configured repositories and agents for an interactive session launcher.

type LaunchRepository

type LaunchRepository struct {
	Name   string
	Remote string
	Source string
}

LaunchRepository is a repository available to an interactive session launch. Source is an existing local checkout used for Hive's normal file-copy behavior; desktop maps this to a narrower presentation DTO.

type LaunchRequest

type LaunchRequest struct {
	Name            string
	Prompt          string
	Agent           string
	Repo            string
	CollisionSuffix string
	Tags            []string
	// Env holds KEY=VALUE pairs for the session's tmux environment.
	Env []string
}

LaunchRequest asks for a detached session the way a launcher does: by name and by a repository that may be any spelling of a configured checkout's remote.

type Lifecycle

type Lifecycle interface {
	CurrentSession(ctx context.Context) (multiplexer.Target, error)
	AttachOrSwitch(ctx context.Context, target multiplexer.Target, streams multiplexer.AttachStreams) error
	RenameSession(ctx context.Context, target multiplexer.Target, newName string) error
	KillSession(ctx context.Context, target multiplexer.Target) error
	KillWindow(ctx context.Context, target multiplexer.Target) error
}

Lifecycle manages existing multiplexer sessions and windows.

type Multiplexer

type Multiplexer interface {
	SessionCreator
	Lifecycle
}

Multiplexer combines the creation and lifecycle operations used by Hive.

type NewSessionRequest

type NewSessionRequest struct {
	Name   string
	Remote string
	// ShCmd runs in the new session's directory after the clone and before
	// windows open. A non-zero exit aborts window creation.
	ShCmd string
}

NewSessionRequest describes a Hive session to create before windows are opened in it.

type OutputStyler

type OutputStyler interface {
	Header(s string) string
	Muted(s string) string
	Text(s string) string
}

OutputStyler styles the headers that hooks and file copies print. The caller supplies it, so this package has no rendering dependency.

type PlainStyler

type PlainStyler struct{}

PlainStyler returns every string unchanged.

func (PlainStyler) Header

func (PlainStyler) Header(s string) string

func (PlainStyler) Muted

func (PlainStyler) Muted(s string) string

func (PlainStyler) Text

func (PlainStyler) Text(s string) string

type RecycleData

type RecycleData struct {
	DefaultBranch string
}

RecycleData contains template data for recycle commands.

type Recycler

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

Recycler handles resetting a session environment for reuse.

func NewRecycler

func NewRecycler(log zerolog.Logger, executor executil.Executor, renderer *tmpl.Renderer) *Recycler

NewRecycler creates a new Recycler.

func (*Recycler) Recycle

func (r *Recycler) Recycle(ctx context.Context, path string, commands []string, data RecycleData, w io.Writer) error

Recycle executes recycle commands sequentially in the session directory. Commands are rendered as Go templates with the provided data. Output is written to the provided writer. If w is nil, output is discarded.

type Risk

type Risk struct {
	UncommittedChanges bool
	UnpushedCommits    bool
}

Risk describes uncommitted or unpushed work that would be lost if a session is deleted or recycled. Only meaningful for active sessions.

func (Risk) HasRisk

func (r Risk) HasRisk() bool

HasRisk returns true if any data would be lost.

type Service

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

Service orchestrates hive session operations.

func NewService

func NewService(
	log zerolog.Logger,
	sessions session.Store,
	gitClient git.Git,
	cfg *config.Config,
	bus *events.EventBus,
	exec executil.Executor,
	renderer *tmpl.Renderer,
	styler OutputStyler,
	stdout, stderr io.Writer,
	client Multiplexer,
) *Service

NewService creates a new Service.

func (*Service) AddWindowsToTmuxSession

func (s *Service) AddWindowsToTmuxSession(ctx context.Context, tmuxName, workDir string, windows []multiplexer.WindowSpec, background bool) error

AddWindowsToTmuxSession adds windows to an existing tmux session.

func (*Service) AttachOrSwitch

func (s *Service) AttachOrSwitch(ctx context.Context, target multiplexer.Target, streams multiplexer.AttachStreams) error

AttachOrSwitch connects to a qualified multiplexer target.

func (*Service) CheckRisk

func (s *Service) CheckRisk(ctx context.Context, sess session.Session) Risk

CheckRisk is CheckSessionRisk for a session the caller has already read.

func (*Service) CheckSessionRisk

func (s *Service) CheckSessionRisk(ctx context.Context, id string) (Risk, error)

CheckSessionRisk checks whether an active session has uncommitted or unpushed changes. Non-active sessions (recycled, corrupted) always return an empty risk. Git errors are treated conservatively: IsClean failures assume dirty; HasUnpushedCommits failures assume no unpushed commits.

func (*Service) CreateFromRequest

func (s *Service) CreateFromRequest(ctx context.Context, req LaunchRequest) (session.Session, error)

CreateFromRequest creates a detached session for req. It prefers a configured local checkout whose remote is equivalent to req.Repo, so the session copies files from it.

A duplicate name returns session.ErrDuplicateName unwrapped, because the caller asks for another name rather than showing a failure. Any other creation failure is a *LaunchError.

func (*Service) CreateSession

func (s *Service) CreateSession(ctx context.Context, opts CreateOptions) (*session.Session, error)

CreateSession creates a new session or recycles an existing one.

func (*Service) CreateSessionWithWindows

func (s *Service) CreateSessionWithWindows(ctx context.Context, req NewSessionRequest, windows []multiplexer.WindowSpec, background bool) (*session.Session, error)

CreateSessionWithWindows creates a new Hive session, optionally runs shCmd in its directory, then opens tmux windows in it. Non-zero shCmd exit aborts window creation.

func (*Service) CurrentSession

func (s *Service) CurrentSession(ctx context.Context) (multiplexer.Target, error)

CurrentSession returns the current multiplexer session identity.

func (*Service) DeleteSession

func (s *Service) DeleteSession(ctx context.Context, id string) error

DeleteSession removes a session and its directory.

func (*Service) DetectRemote

func (s *Service) DetectRemote(ctx context.Context, dir string) (string, error)

DetectRemote gets the git remote URL from the specified directory.

func (*Service) DetectSession

func (s *Service) DetectSession(ctx context.Context) (string, error)

DetectSession returns the session ID for the current working directory. Returns empty string if not in a hive session.

func (*Service) EditSessionTags added in v0.67.0

func (s *Service) EditSessionTags(ctx context.Context, id string, add, remove []string) (session.Session, error)

EditSessionTags adds and then removes tags, leaving the others in place. Two writers that each add a tag both keep theirs, which a read-modify-replace by the caller would not.

func (*Service) GeneratedRemote added in v0.66.0

func (s *Service) GeneratedRemote(repo, itemURL string) string

GeneratedRemote returns the clone URL hive generates for an item's repo. An explicit remote passes through trimmed, and a repo that cannot be expanded returns "". The protocol is the configured preference for either spelling of the repo, and https when none is set.

func (*Service) GetSession

func (s *Service) GetSession(ctx context.Context, id string) (session.Session, error)

GetSession returns a session by ID.

func (*Service) Git

func (s *Service) Git() git.Git

Git returns the git client for use in background operations.

func (*Service) KillTmuxWindow

func (s *Service) KillTmuxWindow(ctx context.Context, target multiplexer.Target) error

KillTmuxWindow kills one qualified tmux window.

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context) ([]session.Session, error)

ListSessions returns all sessions.

func (*Service) OpenTmuxSession

func (s *Service) OpenTmuxSession(ctx context.Context, name, path, remote, targetWindow string, background bool) (multiplexer.LaunchResult, error)

OpenTmuxSession opens (or creates) a tmux session for the given session parameters. It resolves the spawn strategy, renders window templates, and delegates to the spawner.

func (*Service) PreferredRemote added in v0.66.0

func (s *Service) PreferredRemote(repo, itemURL string) string

PreferredRemote is GeneratedRemote when a clone protocol preference applies to the repo, and "" when none does, so a caller that already holds a working remote keeps it unless the user chose a protocol.

func (*Service) Prune

func (s *Service) Prune(ctx context.Context, all bool) (int, error)

Prune removes recycled and corrupted sessions and their directories. If all is true, deletes ALL recycled sessions. If all is false, respects max_recycled limit per repository (keeps newest N).

func (*Service) RecycleSession

func (s *Service) RecycleSession(ctx context.Context, id string, w io.Writer) error

RecycleSession marks a session for recycling and runs recycle commands. The session directory is not moved; only the DB record state changes. Output is written to w. If w is nil, output is discarded.

func (*Service) RenameSession

func (s *Service) RenameSession(ctx context.Context, id, newName string) error

RenameSession changes the name (and slug) of an existing session.

func (*Service) ResolveSessionLaunchRepository

func (s *Service) ResolveSessionLaunchRepository(ctx context.Context, remote string) (LaunchRepository, error)

ResolveSessionLaunchRepository finds the known local checkout whose remote is equivalent to remote (git.EquivalentRemote; local paths match only by exact spelling), which supplies the file-copy Source. The returned Remote is the request's spelling when a clone protocol preference applies to either spelling, so the preference decides what is cloned. With no preference it is the checkout's own spelling.

func (*Service) SessionAtPath

func (s *Service) SessionAtPath(ctx context.Context, path string) (session.Session, bool, error)

SessionAtPath returns the active session whose checkout holds path, and false when path is inside none.

func (*Service) SessionLaunchOptions

func (s *Service) SessionLaunchOptions(ctx context.Context) (LaunchOptions, error)

SessionLaunchOptions lists repositories from configured workspaces followed by existing on-disk Hive sessions. Equivalent remotes (git.EquivalentRemote) are coalesced so a local configured checkout wins over a Hive clone without rewriting either configured URL.

func (*Service) SetSessionGroup

func (s *Service) SetSessionGroup(ctx context.Context, id, group string) error

SetSessionGroup sets or clears the user-assigned group for a session. An empty group clears the assignment.

func (*Service) SetSessionTags added in v0.67.0

func (s *Service) SetSessionTags(ctx context.Context, id string, tags []string) (session.Session, error)

SetSessionTags replaces a session's tags.

func (*Service) SilenceOutput

func (s *Service) SilenceOutput() (restore func())

SilenceOutput redirects all output to io.Discard and returns a restore function that reverts to the previous writers. Call before starting the TUI to prevent hook and spawn output from corrupting the terminal display.

func (*Service) SwitchTmuxSession

func (s *Service) SwitchTmuxSession(ctx context.Context, name string) error

SwitchTmuxSession switches or attaches to a session name.

type SessionCreator

type SessionCreator interface {
	CreateSession(ctx context.Context, spec multiplexer.SessionSpec) error
	OpenSession(ctx context.Context, spec multiplexer.SessionSpec, selection multiplexer.Target) (multiplexer.LaunchResult, error)
	AddWindows(ctx context.Context, target multiplexer.Target, windows []multiplexer.WindowSpec) error
	AttachOrSwitch(ctx context.Context, target multiplexer.Target, streams multiplexer.AttachStreams) error
}

SessionCreator is the interface used by consumers that create and open sessions.

type SpawnData

type SpawnData struct {
	Path       string // Absolute path to session directory
	Name       string // Session name (display name)
	Prompt     string // User-provided prompt (batch only)
	Slug       string // Session slug (URL-safe version of name)
	ContextDir string // Path to context directory
	Owner      string // Repository owner
	Repo       string // Repository name
}

SpawnData is the template context for window templates.

type Spawner

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

Spawner handles terminal spawning with template rendering.

func NewSpawner

func NewSpawner(log zerolog.Logger, renderer *tmpl.Renderer, tmuxClient SessionCreator, stdout, stderr io.Writer) *Spawner

NewSpawner creates a new Spawner.

func (*Spawner) AddWindowsToTmuxSession

func (s *Spawner) AddWindowsToTmuxSession(ctx context.Context, tmuxName, workDir string, windows []multiplexer.WindowSpec, background bool) error

AddWindowsToTmuxSession adds pre-rendered windows to an existing tmux session. Windows without a working directory inherit workDir. If background is false, it switches to the session after adding windows.

func (*Spawner) OpenWindows

func (s *Spawner) OpenWindows(ctx context.Context, windows []config.WindowConfig, data SpawnData, background bool, targetWindow string) (multiplexer.LaunchResult, error)

OpenWindows renders window templates and opens (or creates) a tmux session. If the session already exists, it attaches to it (optionally selecting targetWindow).

func (*Spawner) OpenWindowsWith

func (s *Spawner) OpenWindowsWith(ctx context.Context, windows []config.WindowConfig, data SpawnData, background bool, targetWindow string, renderer *tmpl.Renderer) (multiplexer.LaunchResult, error)

OpenWindowsWith renders window templates using the given renderer and opens (or creates) a tmux session.

func (*Spawner) SpawnWindows

func (s *Spawner) SpawnWindows(ctx context.Context, windows []config.WindowConfig, data SpawnData, background bool) error

SpawnWindows renders window templates and creates a tmux session.

func (*Spawner) SpawnWindowsWith

func (s *Spawner) SpawnWindowsWith(ctx context.Context, windows []config.WindowConfig, data SpawnData, background bool, renderer *tmpl.Renderer, env []string) error

SpawnWindowsWith renders window templates using the given renderer and creates a tmux session whose environment includes env.

Directories

Path Synopsis
Package scripts embeds and extracts bundled helper scripts (hive-tmux, agent-send).
Package scripts embeds and extracts bundled helper scripts (hive-tmux, agent-send).

Jump to

Keyboard shortcuts

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