Documentation
¶
Overview ¶
Package sessions is lectern's second execution mode: an INTERACTIVE agent you work with, rather than a task you hand off.
A task is "go do this, show me the diff". A session is "I am working on this project with Claude, for days". Both run in tmux on a target, but their lifecycles are opposite: a task's session is created and destroyed around one unit of work, while a session outlives many, and the operator attaches to it, detaches, checks it from a phone, and comes back.
The durable unit is the PROJECT, not the conversation. A session's tmux process is disposable; the row, its wraps, and the project's memory are not — which is what makes a six-month project survive the context window that happened to be working on it this week.
Index ¶
- Constants
- Variables
- func CaptureNativeID(ctx context.Context, ex executor.Executor, ...) string
- func ContextPct(pane string) *int
- func DeriveStatus(pane, prevHash string) string
- func DiscoverCommand() string
- func EnvPrefix(env map[string]string) (string, error)
- func HandoffPrompt(path string) string
- func HasSessionCommand(tmuxName string) string
- func Hash(pane string) string
- func IdleFor(s *store.Session) time.Duration
- func KillCommand(tmuxName string) string
- func LegacyMemorySessionKey(id int64) string
- func MatchProject(workdir string, repoPaths map[int64]string) (int64, bool)
- func MemorySessionKey(id int64) string
- func NormalizeBuiltinEntries(raw string) (string, error)
- func NormalizeGroup(value string) (string, error)
- func ParseModelCatalog(raw string) []string
- func ParsePoll(out string) map[string]string
- func ParsePollSnapshot(output string, names []string) (map[string]PollCapture, bool)
- func ParseTimes(out string) (created, activity float64, ok bool)
- func PollCommand(names []string) string
- func Preview(pane string, lines int) string
- func ProbeBootID(ctx context.Context, ex executor.Executor) (string, bool)
- func ProbeConfiguredHome(ctx context.Context, ex executor.Executor, agent, tmuxName string) (string, error)
- func ProbeExactTmux(ctx context.Context, ex executor.Executor, name string) error
- func ProbeTrackingIdentity(ctx context.Context, ex executor.Executor, tmuxName string) (string, error)
- func ResumePrompt(projectName, wrap, priming string) string
- func RunOptsShort() executor.RunOpts
- func SendKeyCommand(tmuxName, key string) (string, bool)
- func SendTextCommand(tmuxName, stagePath string) string
- func TargetFingerprint(t *store.Target) string
- func TaskOutputModeKnown(mode string) bool
- func TaskPermissionArgsConfigured(args []string) bool
- func TimesCommand(tmuxName string) string
- func ValidateSpecs(raw string) error
- func WriteCheckpoint(path string, m CheckpointManifest) error
- type AdoptOpts
- type Candidate
- type CheckpointExecutorFactory
- type CheckpointManifest
- type CheckpointSession
- type CheckpointSkip
- type DBIdentity
- type HandoffOpts
- type HandoffResult
- type ImportReport
- type LaunchConfiguration
- type LaunchOpts
- type Launcher
- type Manager
- func (m *Manager) Adopt(ctx context.Context, o AdoptOpts) (*store.Session, error)
- func (m *Manager) ApplyLaunchProfile(o LaunchOpts) (LaunchOpts, error)
- func (m *Manager) Archive(ctx context.Context, id int64, stop bool) (*store.Session, error)
- func (m *Manager) CancelSetup(ctx context.Context, id int64) error
- func (m *Manager) CancelWorkspaceOperation(ctx context.Context, sessionID, operationID int64) (*store.WorkspaceOperation, error)
- func (m *Manager) Close()
- func (m *Manager) Discover(ctx context.Context) ([]Candidate, error)
- func (m *Manager) Dismiss(id int64) error
- func (m *Manager) EnsureTrackingIdentity(ctx context.Context, row *store.Session) (string, error)
- func (m *Manager) ExactResumeID(agent, id string) string
- func (m *Manager) ExtendWorkspace(ctx context.Context, sessionID, projectID int64, base string) (*store.WorkspaceOperation, error)
- func (m *Manager) InFlight(id int64) bool
- func (m *Manager) Kill(ctx context.Context, id int64) error
- func (m *Manager) Launch(ctx context.Context, o LaunchOpts) (*store.Session, error)
- func (m *Manager) LaunchBackground(ctx context.Context, options LaunchOpts) (*store.Session, error)
- func (m *Manager) LaunchShell(ctx context.Context, targetID int64) (*store.Session, error)
- func (m *Manager) Poll(ctx context.Context)
- func (m *Manager) PrepareStartup() error
- func (m *Manager) PrepareTakeover(ctx context.Context, ex executor.Executor, task *store.Task, ...) (LaunchOpts, error)
- func (m *Manager) ProjectEnv(projectID *int64) map[string]string
- func (m *Manager) RecoverWorkspaceOperation(ctx context.Context, sessionID, operationID int64) (*store.WorkspaceOperation, error)
- func (m *Manager) RecoverWorkspaceOperations(ctx context.Context)
- func (m *Manager) RecoverWorktree(ctx context.Context, id int64) error
- func (m *Manager) Release(ctx context.Context, id int64) error
- func (m *Manager) RemoveWorktree(ctx context.Context, id int64) error
- func (m *Manager) Resolve(s Spec) Spec
- func (m *Manager) RestartNativeCheckpoint(sessionID int64, agent, workdir, home, tmux string)
- func (m *Manager) Restore(ctx context.Context, id int64) (*store.Session, error)
- func (m *Manager) ResumeConversation(ctx context.Context, sourceID int64, cid, name string) (*store.Session, error)
- func (m *Manager) SendKey(ctx context.Context, id int64, key string) error
- func (m *Manager) SendText(ctx context.Context, id int64, text string) error
- func (m *Manager) SessionLaunchConfiguration(row *store.Session) (*LaunchConfiguration, error)
- func (m *Manager) StartHandoff(id int64, o HandoffOpts) error
- func (m *Manager) Startup(ctx context.Context) error
- func (m *Manager) Unarchive(id int64) (*store.Session, error)
- func (m *Manager) WorkspaceAt(targetID int64, directory string) (*worktree.Interactive, error)
- func (m *Manager) WorkspaceOperation(sessionID, operationID int64) (*store.WorkspaceOperation, error)
- func (m *Manager) WorkspaceProgress(ctx context.Context, id int64) (*worktree.Interactive, error)
- type NativeEvidence
- type PollCapture
- type Spec
- type Start
- type TargetConfig
- type TaskSpec
Constants ¶
const ( IdentityVerifiedCurrent = "verified_current" IdentityDurableExplicit = "durable_explicit" IdentityUnknown = "unknown" )
IdentityState says where a native conversation id came from. A durable explicit id is the UUID already stored in the old row (for example, from an explicit native restore); it does not claim the current process still owns that transcript. Unknown is never silently upgraded to a guessed id.
const ( // EnvSessionID is read by Lectern's own client commands and MCP tools. EnvSessionID = "LECTERN_SESSION_ID" // EnvMemorySession is read by the memory provider's MCP server, which stamps // it on every write so "what did this session learn" has an exact answer. EnvMemorySession = "GRIMOIRE_SESSION" )
A session's identity, as the processes inside it see it.
Lectern knew a session by its row id and everything it launched knew nothing: a tool an agent called could only work out where it was by asking tmux, and the memory store recorded the agent's writes under no run at all, so the two systems had no key in common. The id now goes into the environment of everything the session starts, under a name for each reader.
const ( StatusStarting = "starting" // launched, nothing on the pane yet StatusRunning = "running" // the agent is working StatusWaiting = "waiting" // sitting at its prompt, waiting for you StatusIdle = "idle" // quiet, but not obviously at a prompt StatusDead = "dead" // the tmux session is gone )
Statuses a session can be in. These are derived from what the pane is actually doing, never from what lectern asked it to do.
const DiscoverDelimiter = "\x1e---LECTERN-PS---\x1e"
DiscoverDelimiter separates the tmux listing from the process listing.
const PaneLines = 40
PaneLines is how much scrollback a poll pulls back. Enough to read the current state and show a preview, small enough to poll every couple of seconds.
const PollDelimiter = "\x1e---LECTERN-PANE---\x1e"
PollDelimiter separates one session's capture from the next in a batched poll.
RECORD SEPARATOR (0x1E), deliberately not NUL: these delimiters travel inside a shell command line, and exec() truncates argv at the first NUL byte — a NUL delimiter silently cut the command in half on a real target while every mock test passed.
const PollEnd = "ADK-POLL-END-v2"
const ScratchRootEnv = "LECTERN_SCRATCH_ROOT"
ScratchRootEnv names the variable a target can set to move its scratch area.
const StatusInterrupted = "interrupted"
Variables ¶
var ErrAlreadyAdopted = errors.New("this tmux session is already tracked")
ErrAlreadyAdopted means lectern is already watching this tmux session.
var InteractiveAgents = []string{"claude", "codex", "gemini"}
Agents that can be run interactively. Unlike a dispatched task, an interactive session has a human at the keyboard, so there is no permission mode to resolve and no gated-approval requirement — the operator IS the gate.
var Keys = map[string]string{
"enter": "Enter",
"escape": "Escape",
"ctrl-c": "C-c",
"up": "Up",
"tab": "Tab",
}
Keys the operator may send. An allowlist, because this is a raw input channel into a process with the operator's own permissions.
Functions ¶
func CaptureNativeID ¶
func CaptureNativeID(ctx context.Context, ex executor.Executor, agent, workdir, home, tmuxName, tracking string) string
CaptureNativeID invokes the shared identity implementation with the configured native home explicitly. An empty result is inconclusive.
func ContextPct ¶
ContextPct reads the agent's own context gauge off the pane when it shows one. Absent is the normal case (agents only surface it when it starts to matter), so this returns nil rather than a fabricated number.
func DeriveStatus ¶
DeriveStatus decides what a session is doing from its pane.
The order matters: an explicit "working" marker beats everything, then actual change since the last poll, then the shape of the prompt. Anything we cannot justify is `idle` rather than a confident guess.
func DiscoverCommand ¶
func DiscoverCommand() string
DiscoverCommand finds agents the operator started themselves.
This is the half of the problem a task board misses: most long-running agents were launched by hand in a terminal, and a tool that can only see what it started is blind to the actual work. One command, two listings, joined on the pane's tty — `pane_current_command` is NOT usable here, because an agent launched from a login shell leaves bash in the foreground of the pane.
func EnvPrefix ¶
EnvPrefix renders KEY=value pairs for the shell, sorted so a command is stable across runs. This is how a session reaches a local model.
func HandoffPrompt ¶
HandoffPrompt is what we ask a session to write before it is retired.
The point of a handoff is that the PROJECT survives the context window. A conversation is not a durable representation of a piece of software: keeping one alive for months just means everything important eventually lives in whatever survived compaction. A wrap makes the durable unit explicit — the agent states, while it still has the context, what the next one needs.
func HasSessionCommand ¶
HasSessionCommand asks whether a tmux session still exists.
func Hash ¶
Hash fingerprints a pane so a poll can tell "changed" from "quiet" without storing the whole capture.
func IdleFor ¶
IdleFor is how long a session has been quiet — the honest signal behind every status label, and the one the UI shows next to it.
func KillCommand ¶
KillCommand ends a session's tmux process.
func LegacyMemorySessionKey ¶
LegacyMemorySessionKey is the name a session launched by the previous binary exported, and the one its writes are filed under. It is read, never written.
func MatchProject ¶
MatchProject picks the registered project a discovered agent is working in: the longest repo path that contains (or equals) the pane's working directory. Longest wins so a repo nested inside another is preferred over its parent.
func MemorySessionKey ¶
MemorySessionKey is how a session is named in the memory store. It is namespaced because the store is shared: a bare number would collide with any other tool's run ids, and with another Lectern's.
func NormalizeBuiltinEntries ¶
NormalizeBuiltinEntries removes exact built-ins returned by GET /api/agents before settings are persisted. Changed entries are retained as explicit custom overrides; their builtin marker is discarded and never grants built-in capabilities.
func NormalizeGroup ¶
NormalizeGroup gives every client the same stable hierarchy and blank-to-clear behavior. Group names are labels, never filesystem paths.
func ParseModelCatalog ¶
ParseModelCatalog pulls model identifiers out of whatever JSON an agent's catalog command prints.
The shape is the agent's, not ours, so this reads defensively: a top-level array, or the first array of objects found under a key, and from each entry a slug/id/name. Entries a CLI marks hidden are skipped — those are internal models its own picker does not offer either.
func ParsePollSnapshot ¶
func ParsePollSnapshot(output string, names []string) (map[string]PollCapture, bool)
A complete, validated snapshot is required before any session is updated. Missing frames, duplicate names and partial output never imply a dead agent.
func ParseTimes ¶
ParseTimes reads the epoch pair TimesCommand prints.
func PollCommand ¶
PollCommand captures every named session's pane in ONE command.
One exec per target per tick, not one per session: over SSH the round trip dominates, and a board with a dozen live sessions would otherwise spend the whole tick opening channels.
func ProbeBootID ¶
ProbeBootID is Linux-only and deliberately returns unknown on any error.
func ProbeConfiguredHome ¶
func ProbeExactTmux ¶
func ProbeTrackingIdentity ¶
func ResumePrompt ¶
ResumePrompt primes a fresh session with its predecessor's wrap.
func RunOptsShort ¶
RunOptsShort is the timeout used for the quick pane reads that back the readiness wait.
func SendKeyCommand ¶
SendKeyCommand presses one named key in a session.
func SendTextCommand ¶
SendTextCommand types a message into a session and submits it.
It goes through a tmux buffer rather than `send-keys -l` so the text survives verbatim: newlines, quotes and unicode all reach the agent as one paste instead of being re-interpreted as shell syntax or as separate submissions.
func TargetFingerprint ¶
TargetFingerprint is stable across health probes and target row timestamps.
func TaskOutputModeKnown ¶
TaskOutputModeKnown says whether a custom agent's task output can be parsed. "codex" and "claude" are for a custom agent that wraps one of those CLIs (a different provider, a pinned model, extra flags) and so emits its exact stream; the timeline then reads as it does for the built-in agent instead of as generic JSON lines.
func TaskPermissionArgsConfigured ¶
TaskPermissionArgsConfigured distinguishes a real capability mapping from an empty JSON array that would silently claim a mode while emitting no flag.
func TimesCommand ¶
TimesCommand asks tmux when a session started and when it last did anything.
Adoption needs both: an agent you started three days ago should say "up 3d", not "up 4s", and its idle clock should start from tmux's own activity stamp rather than from the moment lectern happened to notice it. It doubles as the existence check, since it fails on a session that is not there.
func ValidateSpecs ¶
ValidateSpecs rejects definitions that could not launch, so a bad one fails at config time rather than as a session that dies on start.
func WriteCheckpoint ¶
func WriteCheckpoint(path string, m CheckpointManifest) error
Types ¶
type AdoptOpts ¶
type AdoptOpts struct {
TargetID int64
TmuxSession string
ProjectID *int64
Name string
Agent string
Model string
Workdir string
}
AdoptOpts identifies the tmux session to take over.
type Candidate ¶
type Candidate struct {
TmuxSession string `json:"tmux_session"`
Agent string `json:"agent"`
Model string `json:"model"`
Workdir string `json:"workdir"`
Command string `json:"command"`
TargetID int64 `json:"target_id"`
TargetName string `json:"target_name,omitempty"`
// Adopted is set when lectern is already tracking this tmux session, so the
// UI can show it as known rather than offering to adopt it twice.
Adopted bool `json:"adopted"`
SessionID int64 `json:"session_id,omitempty"`
ProjectID *int64 `json:"project_id,omitempty"`
// ProjectName is filled when the workdir matches a registered project.
ProjectName string `json:"project_name,omitempty"`
}
Candidate is an agent found running on a target that lectern does not own.
func ParseDiscover ¶
ParseDiscover joins the tmux and process listings into agent candidates.
type CheckpointExecutorFactory ¶
CheckpointExecutorFactory is injected so export can use a real local, SSH, or PCT executor. The exporter never uses the mock registry.
type CheckpointManifest ¶
type CheckpointManifest struct {
Version int `json:"version"`
CreatedAt string `json:"created_at"`
DB DBIdentity `json:"database"`
Sessions []CheckpointSession `json:"sessions"`
}
func ExportCheckpoint ¶
func ExportCheckpoint(ctx context.Context, dbPath string, factory CheckpointExecutorFactory) (CheckpointManifest, error)
func ReadCheckpoint ¶
func ReadCheckpoint(path string) (CheckpointManifest, error)
type CheckpointSession ¶
type CheckpointSession struct {
ID int64 `json:"id"`
CreatedAt float64 `json:"created_at"`
TargetID int64 `json:"target_id"`
TargetFingerprint string `json:"target_fingerprint"`
Name string `json:"name"`
Agent string `json:"agent"`
Model string `json:"model"`
LaunchConfigSHA256 string `json:"launch_config_sha256"`
TmuxSession string `json:"tmux_session"`
TrackingIdentity string `json:"tracking_identity"`
Workdir string `json:"workdir"`
NativeHome string `json:"native_home"`
BootID string `json:"boot_id"`
NativeRecoveryCID string `json:"native_recovery_cid"`
IdentityState string `json:"identity_state"`
}
type CheckpointSkip ¶
type DBIdentity ¶
type DBIdentity struct {
Path string `json:"path"`
Device uint64 `json:"device"`
Inode uint64 `json:"inode"`
}
DBIdentity uses file identity rather than mutable size or mtime. Device and inode remain stable while SQLite updates the database in place.
type HandoffOpts ¶
type HandoffOpts struct {
// Successor starts a fresh session on the same project, primed with the wrap.
Successor bool
// KillOld retires the old session once the wrap is captured.
KillOld bool
// Agent/Model for the successor; empty reuses the old session's.
Agent string
Model string
}
HandoffOpts controls what happens around a wrap.
type HandoffResult ¶
type HandoffResult struct {
WrapID int64 `json:"wrap_id"`
Summary string `json:"summary"`
Session *store.Session `json:"session,omitempty"`
Remembered bool `json:"remembered"`
}
HandoffResult reports what a wrap produced.
type ImportReport ¶
type ImportReport struct {
Imported int `json:"imported"`
Skipped []CheckpointSkip `json:"skipped,omitempty"`
}
func ImportCheckpoint ¶
func ImportCheckpoint(path, dbPath string) (ImportReport, error)
ImportCheckpoint runs after store.Open has migrated the database and before the first poll. It fills only empty recovery fields with the target's old boot id and captured native id. Mismatches are reported per row.
type LaunchConfiguration ¶
type LaunchConfiguration struct {
Version int `json:"version"`
Spec Spec `json:"spec"`
Yolo bool `json:"yolo"`
ProfileID int64 `json:"profile_id,omitempty"`
ProfileName string `json:"profile_name,omitempty"`
}
LaunchConfiguration records declared settings, not the target's ambient environment or the contents of its credential/configuration files. It is private because explicitly configured environment values may contain secrets.
type LaunchOpts ¶
type LaunchOpts struct {
OnReserved func(*store.Session) error `json:"-"`
SetupTimeout float64 `json:"-"`
ProfileID int64
// Configuration is internal: native continuations keep the source launch settings.
Configuration *LaunchConfiguration
GroupPath string
Worktree *worktree.InteractiveOptions
ProjectID *int64
TargetID int64
Name string
Agent string
Model string
Workdir string
// Resume asks the agent to pick up its own previous conversation
// (`claude --continue`), which is what you want when re-opening a project
// you were in yesterday.
Resume bool
ResumeID string
RecoveryCID string
ForkID string
// ReservedID is an internal durable session reservation for task takeover.
ReservedID int64
// ExtraArgs carries already-validated runtime configuration from a task.
ExtraArgs []string
// SkipProjectMCP is set for takeover launches, whose ExtraArgs carry the
// attempt's captured MCP policy. It also covers empty/Codex snapshots where
// provider-specific flags cannot identify that an explicit snapshot exists.
SkipProjectMCP bool
// Env is layered over the agent's and under nothing: it is how a session is
// pointed at a local model (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
Env map[string]string
// Prime is typed into the session once it is up — a project briefing, or a
// predecessor's handoff.
Prime string
// Yolo runs the agent without approval prompts. Defaulted on by the API for
// interactive sessions — see Start.Yolo.
Yolo bool
// Scratch asks for a throwaway working directory on the target instead of a
// project's repository: an empty room to think in. The directory is a real
// git repository, so whatever the work turns into can later be promoted to a
// project and dispatched against without moving anything.
Scratch bool
}
LaunchOpts are the inputs of a new interactive session.
type Launcher ¶
Launcher carries the binary overrides for the built-in agents. Agent binaries often live in ~/.local/bin, which a systemd unit's PATH does not include.
type Manager ¶
type Manager struct {
DB *store.DB
Reg *executor.Registry
Bus *bus.Bus
Launcher Launcher
// Specs resolves an agent name to how it is launched. Injected so the set is
// the operator's, not a constant in this package.
Specs func() []Spec
Memory memory.Provider
Log *slog.Logger
// WorktreeNamespace scopes automatically-created local allocations. Hosted
// managers leave it empty to retain historical paths and branch names.
WorktreeNamespace string
// HandoffTimeout bounds how long we wait for an agent to write its wrap
// before giving up and saying so.
HandoffTimeout time.Duration
// contains filtered or unexported fields
}
Manager owns the lifecycle of every interactive session.
func New ¶
func New(db *store.DB, reg *executor.Registry, b *bus.Bus, l Launcher, mem memory.Provider, log *slog.Logger) *Manager
New builds a session manager.
func (*Manager) ApplyLaunchProfile ¶
func (m *Manager) ApplyLaunchProfile(o LaunchOpts) (LaunchOpts, error)
ApplyLaunchProfile resolves a named profile before creating a session record. Once launched, continuations use the captured configuration, even if the reusable profile is edited or deleted later.
func (*Manager) Archive ¶
Archive retains a record and terminal snapshot after proving the terminal has stopped. A live tracked terminal requires an explicit stop request.
func (*Manager) CancelSetup ¶
CancelSetup records intent before contacting the target. The worker checks that durable intent before starting an agent even if target delivery fails.
func (*Manager) CancelWorkspaceOperation ¶
func (*Manager) Close ¶
func (m *Manager) Close()
Close stops refresh workers before the shared database is closed.
func (*Manager) Discover ¶
Discover finds agents running on every registered target, whether or not lectern started them.
This closes the gap that makes a pure task board useless for long projects: the sessions you care about most are the ones you started by hand, in a terminal, weeks ago. Adopting one is non-destructive — the tmux session is left exactly as it is and lectern simply starts watching it.
func (*Manager) Dismiss ¶
Dismiss drops a dead session from the live list without touching any process.
func (*Manager) EnsureTrackingIdentity ¶
EnsureTrackingIdentity labels an existing live terminal once. It only sets a tmux option and returns the observed marker; promotion persists it after all proof and lifecycle checks pass. It never restarts the process.
func (*Manager) ExactResumeID ¶
ExactResumeID never falls back to the last conversation in a directory.
func (*Manager) ExtendWorkspace ¶
func (*Manager) Launch ¶
Launch starts an interactive agent and records it. The lifecycle lock spans the reservation and the target launch, so a stop cannot remove the old process between recovery's absence check and the replacement launch.
func (*Manager) LaunchBackground ¶
LaunchBackground returns a durable session reservation before target setup. The worker outlives the initiating HTTP request, with a bounded total lifetime.
func (*Manager) LaunchShell ¶
LaunchShell creates a tracked, agent-free shell room on a target.
This deliberately does not pass through launch profiles, agent setup, project memory, or worktree allocation. The room is a target-side scratch directory so it is available on local, SSH, and pct targets alike, while the tmux session and database row keep it resumable after a terminal detaches.
func (*Manager) Poll ¶
Poll refreshes every live session's status from its target.
It batches by target: one capture command per machine per tick, however many sessions are on it. Status is derived from what the pane is actually doing — see DeriveStatus — and `last_activity_at` is only moved when the pane really changed, because "quiet for 40 minutes" is the number an operator acts on.
func (*Manager) PrepareStartup ¶
PrepareStartup performs the fast, local part of restart reconciliation before the HTTP server is exposed. It only reads SQLite and starts checkpoint workers; target probes and recovery launches remain in the scheduler's asynchronous poll so a slow SSH target cannot hide the API after boot.
func (*Manager) PrepareTakeover ¶
func (m *Manager) PrepareTakeover(ctx context.Context, ex executor.Executor, task *store.Task, project *store.Project, att *store.Attempt, env map[string]string) (LaunchOpts, error)
PrepareTakeover preserves the task's runtime configuration while removing broker hooks tied to the background attempt. Nothing is launched here.
func (*Manager) ProjectEnv ¶
ProjectEnv is the environment a project asks its agents to run with — the any-model door, shared by dispatched tasks and interactive sessions.
func (*Manager) RecoverWorkspaceOperation ¶
func (*Manager) RecoverWorkspaceOperations ¶
func (*Manager) RecoverWorktree ¶
func (*Manager) Release ¶
Release stops tracking a session and LEAVES ITS PROCESS RUNNING.
This is the counterpart to Adopt. Adoption is non-destructive — it just starts watching a terminal the operator already had open — so letting go of one has to be non-destructive too, or "add it to the board" quietly becomes "hand its life over to the board".
func (*Manager) RemoveWorktree ¶
func (*Manager) Resolve ¶
specs is the agent set, falling back to the built-ins when none is injected. Resolve fills a spec's binary in from configuration, so a caller sees the command that would actually run rather than the name it was defined with.
func (*Manager) RestartNativeCheckpoint ¶
RestartNativeCheckpoint changes only Lectern's read-only observer after a promotion; the user's existing process and tmux terminal remain untouched.
func (*Manager) Restore ¶
Restore resumes monitoring the original adopted tmux session. It never launches an agent, recreates tmux or guesses a native conversation ID.
func (*Manager) ResumeConversation ¶
func (m *Manager) ResumeConversation(ctx context.Context, sourceID int64, cid, name string) (*store.Session, error)
ResumeConversation starts an exact native conversation after its old terminal has stopped. History validation belongs to the API's target-side reader.
func (*Manager) SendKey ¶
SendKey presses one allowlisted key in a session — Escape to interrupt a turn, Enter to accept, and so on.
func (*Manager) SendText ¶
SendText types a message into a session and submits it — the phone-side equivalent of typing at the terminal.
func (*Manager) SessionLaunchConfiguration ¶
func (m *Manager) SessionLaunchConfiguration(row *store.Session) (*LaunchConfiguration, error)
SessionLaunchConfiguration falls back to current settings only for records predating snapshots or adopted terminals whose original settings are unknown.
func (*Manager) StartHandoff ¶
func (m *Manager) StartHandoff(id int64, o HandoffOpts) error
StartHandoff asks a session to write its wrap and finishes the job in the background: an agent mid-turn can take minutes to answer, and the operator should not sit on a hanging request to find that out.
func (*Manager) Startup ¶
Startup performs one bounded reconciliation for callers that explicitly need synchronous startup behavior. The hosted app uses PrepareStartup and lets the scheduler perform the remote poll asynchronously.
func (*Manager) WorkspaceAt ¶
WorkspaceAt resolves a grouped allocation shared by fresh forks or resumed sessions. Sharing the directory never gives another session removal ownership.
func (*Manager) WorkspaceOperation ¶
func (m *Manager) WorkspaceOperation(sessionID, operationID int64) (*store.WorkspaceOperation, error)
func (*Manager) WorkspaceProgress ¶
WorkspaceProgress reads an atomic target receipt without blocking a live checkout or overwriting the launcher's newer database state.
type NativeEvidence ¶
type NativeEvidence struct {
State string `json:"state"`
ID string `json:"id"`
PID int `json:"pid"`
ProcStart string `json:"proc_start"`
Workspace string `json:"workspace"`
RootPID int `json:"root_pid"`
RootStart string `json:"root_start"`
PaneID string `json:"pane_id"`
NativeHome string `json:"native_home"`
BootID string `json:"boot_id"`
}
NativeEvidence is the read-only proof that a native conversation belongs to the interactive process currently occupying a tracked terminal.
func CaptureNativeEvidence ¶
func CaptureNativeEvidence(ctx context.Context, ex executor.Executor, agent, workdir, home, tmuxName, tracking string, discovery bool) (NativeEvidence, error)
CaptureNativeEvidence resolves the native identity in one target-side probe. It deliberately returns no identity when the process, transcript, or pane changes during the probe; callers must treat that as a hard validation error.
type PollCapture ¶
type Spec ¶
type Spec struct {
Name string `json:"name"`
// Command is the binary (or a full shell command) that starts it.
Command string `json:"command"`
// Args are fixed arguments appended on every launch.
Args []string `json:"args,omitempty"`
// ModelFlag passes a model, e.g. "--model" or "-m". Empty means this CLI has
// no model switch and any model set on the session is ignored rather than
// guessed at.
ModelFlag string `json:"model_flag,omitempty"`
// ResumeArgs reopen the CLI's own previous conversation, e.g. ["--continue"].
// Empty means resume is not offered for this agent.
ResumeArgs []string `json:"resume_args,omitempty"`
// ResumeIDArgs select one exact conversation. {id} and {dir} are substituted
// before shell quoting; {dir} follows the recorded working directory.
ResumeIDArgs []string `json:"resume_id_args,omitempty"`
ForkArgs []string `json:"fork_args,omitempty"`
// PromptArg says the opening message can be a positional argument. When it
// cannot, lectern falls back to typing the message once the pane settles.
PromptArg bool `json:"prompt_arg,omitempty"`
// Env is agent-wide environment, layered under the project's own. This is
// the local-model door for a CLI that wants its endpoint in the environment.
Env map[string]string `json:"env,omitempty"`
// TrustCommand marks a directory as one the operator already trusts, in
// whatever file the CLI keeps that answer in. `{dir}` is replaced with the
// shell-quoted working directory.
//
// Every coding CLI asks "do you trust this folder?" the first time it opens
// one, and answers it in its own config. Launching an agent there IS the
// answer — lectern was told to start it, in that directory, on purpose —
// so being asked again in a terminal you then have to go and find is pure
// friction. It bites hardest on scratch sessions, where the directory is new
// every single time and the prompt is therefore guaranteed.
TrustCommand string `json:"trust_command,omitempty"`
// YoloArgs drop the CLI's approval prompts so the agent just works. Every
// coding CLI spells this differently and some cannot do it at all; empty
// means this agent has no such mode and the toggle is not offered for it.
YoloArgs []string `json:"yolo_args,omitempty"`
// ModelsCommand asks the CLI what models it has. `{bin}` is replaced with the
// resolved binary. Model line-ups change faster than lectern ships, and a
// list of names written down here is wrong the moment a vendor renames one —
// so the tool is asked rather than remembered. Empty means no catalog, and
// the UI falls back to whatever you have already run.
ModelsCommand string `json:"models_command,omitempty"`
// Task is optional because a configured CLI may be interactive-only. Its
// command/args are independent from the interactive invocation above.
Task *TaskSpec `json:"task,omitempty"`
// Builtin marks the three that ship with lectern, so the UI can show which
// are yours.
Builtin bool `json:"builtin,omitempty"`
}
Spec describes how to start one interactive coding CLI.
Three agents ship built in, but the set is deliberately open: the terminal does not care which binary is in it, and neither should the board. A spec is the smallest description that lets lectern launch, resume and prime an arbitrary CLI — anything beyond that is the CLI's business.
func ParseSpecs ¶
ParseSpecs decodes the operator's custom agents and merges them over the built-ins. Same name overrides, so a built-in whose CLI has drifted can be corrected without a new release.
func (Spec) LaunchCommand ¶
LaunchCommand builds the tmux command that starts one interactive session.
func (Spec) ModelsProbe ¶
ModelsProbe is the command that asks this agent for its model catalog, with the binary resolved. Empty when the agent cannot be asked.
func (Spec) TrustProbe ¶
TrustProbe is the command that marks a directory trusted for this agent, or empty when the agent has no such notion.
type Start ¶
type Start struct {
SetupToken string
Workdir string
TmuxName string
Model string
Resume bool
ResumeID string
ForkID string
Prompt string
EnvPrefix string
// Yolo runs the agent without its approval prompts. On by default for
// interactive sessions: you are sitting in the terminal watching it, which
// is the supervision, and being asked to confirm every edit in a session you
// opened on purpose is just friction. An agent with no YoloArgs ignores it.
Yolo bool
// ToolArgs are provider-specific configuration flags supplied by the
// project. They are quoted here because they may contain MCP secrets.
ToolArgs []string
}
LaunchCommand renders the tmux invocation that starts this agent. Start is everything that varies between one launch of an agent and the next.
type TargetConfig ¶
type TargetConfig struct {
Kind string `json:"kind"`
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
KeyPath string `json:"key_path"`
CommandPrefix string `json:"command_prefix"`
}
TargetConfig is the target connection identity used to establish an executor. Display and scheduling fields are intentionally omitted: renaming a target or changing its concurrency must not discard a valid checkpoint.
type TaskSpec ¶
type TaskSpec struct {
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
PromptTemplate string `json:"prompt_template"`
OutputMode string `json:"output_mode,omitempty"`
PermissionArgs map[string][]string `json:"permission_args,omitempty"`
// ResumeArgs continue the CLI's own previous run for a follow-up, with
// {id} replaced by the session id captured from its output, e.g.
// ["resume", "{id}"] for a codex wrapper. Empty means a follow-up starts a
// fresh process in the same worktree.
ResumeArgs []string `json:"resume_args,omitempty"`
}
TaskSpec describes a configured CLI's non-interactive one-shot command. PromptTemplate is appended to the command and must contain {prompt} or {prompt_file}; stdin is also supported when the value is exactly "stdin".
Source Files
¶
- adopt.go
- agents.go
- archive.go
- background_launch.go
- boot.go
- checkpoint_manifest.go
- claude_fork_path.go
- db_identity_unix.go
- discover.go
- groups.go
- handoff.go
- identity.go
- interactive_worktree.go
- launch_configuration.go
- manager.go
- memory_context.go
- native_directory.go
- native_evidence.go
- native_id.go
- poll.go
- poll_wire.go
- recovery.go
- restore.go
- resume.go
- sessions.go
- setup_cancel.go
- setup_recovery.go
- stop.go
- takeover.go
- trust_compat.go
- workspace_lifecycle.go
- workspace_operations.go