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 AgentExited(row *store.Session, p AgentProbe) bool
- func CaptureNativeID(ctx context.Context, ex executor.Executor, ...) string
- func CatalogConversations(ctx context.Context, ex executor.Executor, spec Spec, workdir, cid string) (map[string]json.RawMessage, error)
- func CatalogConversationsCommand(spec Spec, workdir, cid string) (string, error)
- func CatalogGroups() []string
- func ContextPct(pane string) *int
- func DeriveStatus(pane, prevHash string) string
- func DiscoverCommand() string
- func EnvPrefix(env map[string]string) (string, error)
- func ExcerptPrompt(projectName, excerpt, priming string) string
- func HandoffPrompt(path string) string
- func HasBusyMarker(pane string) bool
- 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 LimitResumePrompt(projectName, wrap, priming string) string
- func MatchAdoptedConversation(candidates []NativeCandidate, lastActive, ended float64, taken map[string]bool) string
- func MatchLaunchedConversation(convs []CatalogConversation, launchedAt float64, ...) (id string, ambiguous bool)
- 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 ACPSpec
- type AdoptOpts
- type AgentProbe
- type Candidate
- type Capability
- type CapabilityState
- type CatalogConversation
- type CatalogIcon
- type CatalogPreset
- type CheckpointExecutorFactory
- type CheckpointManifest
- type CheckpointSession
- type CheckpointSkip
- type ContinueOpts
- type DBIdentity
- type HandoffOpts
- type HandoffResult
- type HandoffStatus
- 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) Continue(ctx context.Context, sourceID int64, o ContinueOpts) (*store.Session, error)
- 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) Handoff(id int64) (HandoffStatus, bool)
- func (m *Manager) HandoffError(id int64) string
- 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) LaunchAccountLogin(ctx context.Context, accountID int64) (*store.Session, error)
- func (m *Manager) LaunchBackground(ctx context.Context, options LaunchOpts) (*store.Session, error)
- func (m *Manager) LaunchProjectShell(ctx context.Context, projectID int64) (*store.Session, error)
- func (m *Manager) LaunchShell(ctx context.Context, targetID int64) (*store.Session, error)
- func (m *Manager) LaunchShellIn(ctx context.Context, targetID int64, dir, name string, projectID *int64) (*store.Session, error)
- func (m *Manager) MatchLostAdopted(ctx context.Context, id int64) string
- 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) Reach(targetID int64) TargetReach
- 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) Relaunch(ctx context.Context, id int64, prime string) (*store.Session, error)
- func (m *Manager) Release(ctx context.Context, id int64) error
- func (m *Manager) RemoveWorktree(ctx context.Context, id int64) error
- func (m *Manager) ReopenShell(ctx context.Context, id int64) (*store.Session, 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) Retire(ctx context.Context, id int64) (*store.Session, error)
- func (m *Manager) SendKey(ctx context.Context, id int64, key string) error
- func (m *Manager) SendNotice(ctx context.Context, id int64, text string) error
- func (m *Manager) SendNudge(ctx context.Context, id int64, text 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) SetAgentProbeInterval(every time.Duration)
- func (m *Manager) StartHandoff(id int64, o HandoffOpts) error
- func (m *Manager) StartLimitHandoff(id int64, agent, model string, profileID int64) error
- func (m *Manager) Startup(ctx context.Context) error
- func (m *Manager) SwapAccount(ctx context.Context, id, accountID int64) (bool, 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 NativeCandidate
- type NativeEvidence
- type PollCapture
- type SessionsSpec
- type Spec
- func (s Spec) AssignsSessionID(resume bool, resumeID, forkID string) bool
- func (s Spec) Capabilities() map[Capability]CapabilityState
- func (s Spec) ExactConversations() bool
- func (s Spec) Installed() bool
- func (s Spec) LaunchCommand(o Start) string
- func (s Spec) ModelsProbe() string
- func (s Spec) TakesPrompt() bool
- func (s Spec) TrustProbe(dir string) string
- type Start
- type TargetConfig
- type TargetReach
- type TaskSpec
Constants ¶
const ( CatalogGroupPopular = "Popular" CatalogGroupVendor = "Vendor agents" CatalogGroupCommunity = "Open source & community" CatalogGroupAdapters = "ACP adapters" )
Catalog groups, in display order.
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 ( // MaxConcurrentTargetPolls bounds how many machines are polled at once. MaxConcurrentTargetPolls = 8 // DefaultTargetPollTimeout bounds one target's whole poll (boot probe, // pane capture, recovery). DefaultTargetPollTimeout = 20 * time.Second // DefaultPollWait is how long Poll waits for this round's targets before // returning, which is also the most a slow target can delay the // scheduler's tick. A target still in flight keeps running in the // background and is skipped by later rounds until it finishes. DefaultPollWait = 500 * time.Millisecond // UnreachableAfter is how long a poll may run before its target is shown // as unreachable, without waiting for the timeout. UnreachableAfter = 8 * time.Second )
Status polling is per target and independent: each machine is polled by its own worker, a bounded number at a time, under its own timeout. Before this, Poll visited targets one after another, so one unreachable machine stalled status for every other machine for up to the poll command's 45s timeout — and, because the scheduler waits for Poll, stalled task scheduling with it.
const ( EndStopped = "stopped" // ended from Lectern: End, Kill, Stop and archive EndExited = "exited" // the terminal went away on its own EndReleased = "released" // tracking stopped; the process was left running EndHandedOff = "handed_off" // retired after a handoff started its successor EndDismissed = "dismissed" // a dead card was dismissed EndFailed = "failed" // the launch or its setup never completed EndRestart = "restart" // lost to a host restart and replaced on reopen )
End reasons recorded in sessions.end_reason. Restore uses them to say what happened to a session and what reopening it brings back.
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 ( // EnvClaudeDisableMouse is the variable Claude Code (and OpenClaude, its // fork) reads. EnvClaudeDisableMouse = "CLAUDE_CODE_DISABLE_MOUSE" // TerminalMouseSetting is the global settings row: on unless it is "0". // A project's claude_terminal_mouse column overrides it with "1" or "0". TerminalMouseSetting = "claude_terminal_mouse" )
Leaving the mouse to the terminal in Claude Code.
Claude Code's fullscreen renderer ("tui": "fullscreen") turns on full mouse tracking, so the terminal forwards every click to Claude: native selection and copy, clicking a link, and Lectern's own clickable file paths and right-click menu all stop working in its sessions. CLAUDE_CODE_DISABLE_MOUSE keeps the fullscreen rendering and leaves the mouse alone. People who set it in ~/.bashrc do not get it here: Lectern launches through a non-interactive `bash -c`, which reads no rc file. So Lectern sets it itself.
const AgentProbeMarker = ": LECTERN-AGENT-PROBE;"
AgentProbeMarker starts the probe command; the mock executor keys on it.
const CatalogPluginID = "lectern.agent-catalog"
CatalogPluginID is the bundled plugin that carries the catalog.
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 ErrAgentExited = limits.ErrAgentExited
ErrAgentExited is a swap whose agent quit straight after its restart: there is nothing running to resume.
var ErrAlreadyAdopted = errors.New("this tmux session is already tracked")
ErrAlreadyAdopted means lectern is already watching this tmux session.
var HandoffPollInterval = 3 * time.Second
HandoffPollInterval is the default for Manager.HandoffPoll: how often a handoff checks whether the agent has finished writing its wrap. Agents take seconds to minutes to write one, so checking more often buys nothing in production; tests lower it so each handoff does not cost a fixed three seconds of waiting.
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 AgentExited ¶ added in v2.4.0
func AgentExited(row *store.Session, p AgentProbe) bool
AgentExited decides from a probe whether a session's agent has gone while its terminal remains. Lectern-launched agents are exact: the pane's root process becomes a bare `bash` only after the agent command returned. For an adopted session the foreground must be a shell and no process on its terminal may still look like the agent.
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 CatalogConversations ¶ added in v2.6.0
func CatalogConversations(ctx context.Context, ex executor.Executor, spec Spec, workdir, cid string) (map[string]json.RawMessage, error)
CatalogConversations runs CatalogConversationsCommand and returns its raw JSON document, or the reader's own error message.
func CatalogConversationsCommand ¶ added in v2.6.0
CatalogConversationsCommand is the target-side command that lists (cid empty) or validates (cid set) a catalog agent's saved conversations in workdir. spec must already be resolved and have Sessions set.
func CatalogGroups ¶ added in v2.6.0
func CatalogGroups() []string
CatalogGroups is the display order of the groups above.
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 ExcerptPrompt ¶ added in v2.4.0
ExcerptPrompt primes a successor with what a session left behind when it wrote no handoff — worded so the agent does not mistake it for one.
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 HasBusyMarker ¶ added in v2.4.0
HasBusyMarker reports whether the bottom of a pane shows the agent working ("esc to interrupt"), as opposed to DeriveStatus's broader "running", which also counts any pane change.
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 LimitResumePrompt ¶ added in v2.4.0
LimitResumePrompt primes a successor that takes over because its predecessor hit a usage limit: unlike ResumePrompt, it should carry on.
func MatchAdoptedConversation ¶ added in v2.4.0
func MatchAdoptedConversation(candidates []NativeCandidate, lastActive, ended float64, taken map[string]bool) string
MatchAdoptedConversation picks the conversation whose last write is near the session's last activity, or "" when there is none or more than one. Conversations already bound to another session are never chosen.
func MatchLaunchedConversation ¶ added in v2.6.0
func MatchLaunchedConversation(convs []CatalogConversation, launchedAt float64, taken, existing map[string]bool) (id string, ambiguous bool)
MatchLaunchedConversation picks the conversation created by one launch, never one another session holds. existing, when known, is every conversation listed just before the launch: anything absent from it and written since is new, which also covers a fork whose CLI copies its parent's creation time. Without it, the conversation must have been created at or after launchedAt (less captureSlack). It returns "" with ambiguous=true when more than one qualifies.
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 ACPSpec ¶ added in v2.4.0
type ACPSpec struct {
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
}
ACPSpec is the ACP invocation for a configured agent: the command to spawn (it speaks JSON-RPC over its own stdio — see internal/drivers/acp.go), e.g. Command:"npx" Args:["-y","@zed-industries/claude-code-acp"], or Command:"gemini" Args:["--experimental-acp"] once gemini is on PATH.
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 AgentProbe ¶ added in v2.4.0
AgentProbe is what the target said about one pane.
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 Capability ¶ added in v2.4.0
type Capability string
Capability names a feature a session/task picker might offer. Kept as exported string constants (not an unexported iota) because they double as the JSON keys in CapabilityState maps returned to the frontend and TUI.
const ( CapResume Capability = "resume" CapForkTo Capability = "fork" CapModel Capability = "model" CapModelsList Capability = "models_list" CapYolo Capability = "yolo" CapACP Capability = "acp" CapTask Capability = "task" // CapExact is resuming or forking one exact conversation later: the // built-ins by process evidence, catalog agents by an id named at launch // or read from where the CLI lists its sessions. CapExact Capability = "exact" )
type CapabilityState ¶ added in v2.4.0
type CapabilityState struct {
Available bool `json:"available"`
Reason string `json:"reason,omitempty"`
}
CapabilityState is whether one Capability is available for a Spec, and — when it is not — a short, name-specific reason a picker can show instead of a disabled control with no explanation ("Resume isn't available for Aider") rather than a plain grey-out nobody can act on.
type CatalogConversation ¶ added in v2.6.0
type CatalogConversation struct {
ID string `json:"id"`
Title string `json:"title"`
Created *float64 `json:"created"`
Modified *float64 `json:"modified"`
}
CatalogConversation is one saved conversation a catalog CLI lists.
type CatalogIcon ¶ added in v2.6.0
CatalogIcon is a one- or two-letter badge on a brand-neutral color.
type CatalogPreset ¶ added in v2.4.0
type CatalogPreset struct {
Spec
// DisplayName is UI copy; it need not match the binary name.
DisplayName string `json:"display_name"`
// Vendor is who ships the CLI; the catalog search matches it.
Vendor string `json:"vendor"`
// Group sections the catalog list so ~30 entries stay scannable.
Group string `json:"group"`
// Icon is a monogram badge. Lectern ships no third-party logos: they are
// trademarks, and fetching favicons would call out to a third party
// every time Settings opens.
Icon CatalogIcon `json:"icon"`
// Homepage is the CLI's own documentation.
Homepage string `json:"homepage"`
// Description is one line of UI copy: what the CLI is, and anything a
// reviewer should know before adding it — especially what it cannot do.
Description string `json:"description"`
// InstallHint is copy-pasteable install guidance shown when Installed()
// is false for the launch host.
InstallHint string `json:"install_hint"`
// SessionsHint says where the CLI's own session ids are listed, for an
// exact resume or fork. Lectern captures native ids itself only for the
// built-in agents.
SessionsHint string `json:"sessions_hint,omitempty"`
// Source is where the flags below were read, so a stale entry can be
// re-checked against the same page instead of re-discovered from scratch.
Source string `json:"source"`
// VerifiedBy is "<binary> <version>" when the flags were checked against
// that installed CLI's --help (and, for ACP, a real initialize handshake),
// or "docs" when only the vendor's documentation could be read.
VerifiedBy string `json:"verified_by"`
// Unverified lists Spec JSON field names (e.g. "model_flag",
// "resume_args") that are a best guess rather than a confirmed fact as of
// VerifiedAt. A field absent from this list, including one left at its
// zero value, was confirmed to genuinely be unsupported — not merely
// unresearched.
Unverified []string `json:"unverified,omitempty"`
// VerifiedAt is when the entry was last checked (YYYY-MM-DD).
VerifiedAt string `json:"verified_at"`
}
CatalogPreset is a one-click starting point for Settings → Agents: a Spec for a popular third-party coding CLI, plus the metadata a reviewer needs to trust it. Unlike Builtins(), lectern does not maintain these binaries — their flags are only as good as the day someone last checked them, and a preset that quietly goes stale is worse than one that says so.
Every preset below says how it was checked in VerifiedBy (the installed CLI version whose --help it was read from, or "docs" when the CLI could not be installed without an account), cites the page(s) it was read from in Source, and lists in Unverified any Spec field that could not be confirmed — those fields hold a best guess and the UI presents them as unconfirmed. Re-check before trusting a preset whose VerifiedAt has aged.
func Catalog ¶ added in v2.4.0
func Catalog() []CatalogPreset
Catalog lists the coding CLIs Settings → Agents offers as a one-click "Add from catalog" starting point, on top of the "Custom command…" escape hatch the editor already has. Adding one here never changes behavior for an operator who already saved a custom agent under the same name — ParseSpecs only ever reads what is in the "agents" setting; a preset is just what pre-fills the editor the first time.
The entries are the bundled lectern.agent-catalog plugin (internal/pluginpkg/bundled/agent-catalog/lectern-plugin.yaml): the catalog is a plugin contribution like any other, so the plugin path is exercised by real content. Installed plugins add their own presets beside these (internal/plugins); this function is only the bundled set.
A preset whose CLI speaks the Agent Client Protocol gets an ACP field in addition to its interactive launch fields: per docs/acp.md, ACP only ever replaces the Task backend for headless work (tasks/routines/best-of-N/evals) — interactive sessions stay tmux-based through Command/Args/PromptArg(s) exactly like every other agent. ACP is preferred over a Task command whenever both exist, because it carries every permission mode and project MCP servers itself.
func CatalogFromRaw ¶ added in v2.6.0
func CatalogFromRaw(raw []json.RawMessage) ([]CatalogPreset, error)
CatalogFromRaw decodes plugin agent contributions into presets. Unknown fields are errors, so a preset cannot carry a flag Lectern would ignore.
func FindCatalogPreset ¶ added in v2.4.0
func FindCatalogPreset(name string) (CatalogPreset, bool)
FindCatalogPreset looks up one catalog entry by name for the "Add from catalog" flow.
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 ContinueOpts ¶ added in v2.4.0
type ContinueOpts struct {
Agent string
Model string
ProfileID int64
Name string
// Context is what the successor is primed with: the latest wrap, or an
// excerpt of the saved conversation. Empty starts the successor fresh.
Context string
// WrapID is the wrap Context came from, if any. A wrap nobody continued
// yet is linked to the successor, so it shows where it came from.
WrapID int64
// Excerpt marks Context as material the old session left behind (the end
// of its conversation or screen) rather than a handoff it wrote.
Excerpt bool
}
ContinueOpts picks the successor for Continue.
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
ProfileID int64
// QuickSwitch treats an empty model as the destination's default.
QuickSwitch bool
// Continue primes the successor to carry on with the work rather than
// report and wait — used when a usage limit, not the operator, is the
// reason for the switch (docs/rate-limits.md).
Continue bool
// contains filtered or unexported fields
}
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 HandoffStatus ¶ added in v2.4.0
type HandoffStatus struct {
Phase string `json:"phase"` // saving | starting
Destination string `json:"destination,omitempty"` // what the successor will be
SuccessorID int64 `json:"successor_id,omitempty"`
}
HandoffStatus is the observable progress of a switch. A switch is two separate operations — the predecessor writing its wrap, then the successor starting — and the operator should be able to see which one is running instead of watching an opaque "Switching…".
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"`
// PermissionMode records whether this launch registered the
// PermissionRequest hook ("ask") or not ("bypass"/empty), so a
// continuation of this exact session keeps behaving the same way
// without the caller having to know or re-specify it.
PermissionMode string `json:"permission_mode,omitempty"`
// ProfileInstructions is the selected profile's launch briefing, captured
// with the rest of the settings so a continuation reuses the briefing the
// session started with rather than a later edit of the reusable profile.
// It is text delivered to the agent, never configuration: it cannot change
// the spec, environment, model or approvals.
ProfileInstructions string `json:"profile_instructions,omitempty"`
// Isolation is this launch's sandbox tier (none/bwrap/docker) and network
// policy — see internal/isolation. Captured here so a resume/relaunch of
// this exact session keeps running the way it started even if the
// project's own default changes later.
Isolation isolation.Config `json:"isolation,omitempty"`
// TerminalMouse says Spec.Env's CLAUDE_CODE_DISABLE_MOUSE was set by
// Lectern rather than by a person (terminal_mouse.go), so a continuation
// re-decides it from the current setting instead of keeping it.
TerminalMouse bool `json:"terminal_mouse,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
// PermissionMode is "bypass"|"ask" (docs/agent-events.md section 3),
// resolved by the API layer (explicit request field, else the
// "session_permission_mode" global default setting) for the primary
// interactive-session launch path. Left empty by every other caller
// (task takeover, handoff, scratch shells) on purpose: those already
// compute Yolo their own way for reasons unrelated to this feature, and
// an empty PermissionMode here means "do not additionally register the
// PermissionRequest hook for this launch" — it does not change Yolo.
PermissionMode string
// 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
// SkipPrime types nothing into the new process: an account swap resumes a
// conversation that already has its briefing, and the limits tracker
// types the one nudge itself.
SkipPrime bool
// AccountID records which registered login (docs/accounts.md) this launch
// runs under; nil leaves the row's account as it is. The caller puts the
// account's directory in the environment.
AccountID *int64
// Isolation overrides the project's (or the built-in) default sandbox
// tier for this one launch — nil defers to that default entirely. See
// internal/isolation. Ignored for a continuation (o.Configuration != nil
// already carries the original launch's Isolation forward).
Isolation *isolation.Config
}
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
// PluginMCP returns the MCP servers enabled plugins add for a project on
// a target (internal/plugins); the project's own servers win on a name.
PluginMCP func(ctx context.Context, ex executor.Executor, targetID, projectID int64, taken map[string]bool) (map[string]any, error)
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
// HookBase is the host part every launched session's LECTERN_HOOK_URL is
// built from (see internal/agentevents). Empty falls back to
// "http://127.0.0.1:9110" only in the sense that an empty value here
// means the caller (app.New) did not set config.Config.HookBase/BaseURL —
// production always does.
HookBase string
// AskPermission, when true, forces every newly launched Claude session
// to register the PermissionRequest hook (docs/agent-events.md section
// 3), regardless of LaunchOpts.PermissionMode. Never set by app.New
// today — the real per-launch/global-default control is
// LaunchOpts.PermissionMode, resolved by the API layer from the
// request or the "session_permission_mode" setting. This field remains
// as a hard operator override (e.g. a future config knob) that cannot
// be turned off per launch.
AskPermission bool
// Checks, when set, is told when the screen-derived status moves a
// session from busy/working (StatusRunning) to idle (StatusIdle) — see
// applyPane in poll.go. This is the fallback trigger for a session's
// check command on targets/agents with no lifecycle hooks; a hooked
// session's Stop event (internal/agentevents) triggers the same runner
// independently, and the runner's own worktree fingerprint is what keeps
// the two triggers from ever double-running a check.
Checks agentevents.StopListener
// IsolationProxies holds each isolated session's egress allowlist proxy
// (bwrap network=deny only — see internal/isolation) for as long as the
// session is running; started in launch, always torn down in end().
IsolationProxies *isolation.ProxyRegistry
// HandoffTimeout bounds how long we wait for an agent to write its wrap
// before giving up and saying so.
HandoffTimeout time.Duration
// HandoffPoll overrides HandoffPollInterval when positive.
HandoffPoll time.Duration
// TargetPollTimeout and PollWait override DefaultTargetPollTimeout and
// DefaultPollWait when positive (see reach.go).
TargetPollTimeout time.Duration
PollWait time.Duration
// Limits sees every pane capture so a usage-limit stop is noticed
// (internal/limits, docs/rate-limits.md). Nil disables detection.
Limits *limits.Tracker
// 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) Continue ¶ added in v2.4.0
func (m *Manager) Continue(ctx context.Context, sourceID int64, o ContinueOpts) (*store.Session, error)
Continue starts a new session in a closed session's place — same project, folder and group — optionally with a different agent, model or launch profile, primed with the context it is given. It reuses the handoff launch rules. The closed record is left untouched.
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) Handoff ¶ added in v2.4.0
func (m *Manager) Handoff(id int64) (HandoffStatus, bool)
Handoff comes back with the phase of a switch that is still running, and the successor id once one has started. Reloading the page mid-switch must not lose either.
func (*Manager) HandoffError ¶ added in v2.4.0
HandoffError is the reason the last switch on this session failed, kept until the next one starts so a reload can still explain what happened.
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) LaunchAccountLogin ¶ added in v2.6.0
LaunchAccountLogin opens a tracked shell on the account's target with the account's directory in the environment and the CLI's own sign-in running in it. The operator finishes the sign-in in the web terminal; Lectern never sees what is typed there or what the CLI stores.
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) LaunchProjectShell ¶ added in v2.4.0
LaunchProjectShell opens a fresh tracked, agent-free shell directly in a project's repository. The target and directory come from the stored project, never from the caller, and a missing repository fails instead of silently falling back to a scratch room or the target user's home. Unlike the preexisting project terminal, every call creates a new tracked session whose tmux name and identity are its own.
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) LaunchShellIn ¶ added in v2.6.1
func (m *Manager) LaunchShellIn(ctx context.Context, targetID int64, dir, name string, projectID *int64) (*store.Session, error)
LaunchShellIn opens a fresh tracked, agent-free shell on a target in dir — what a split of a native attachment opens beside an agent (docs/terminal-client.md). dir comes from the server's own records or the agent's pane, never from a client; a directory that is gone is refused.
func (*Manager) MatchLostAdopted ¶ added in v2.4.0
MatchLostAdopted looks for a lost adopted session's conversation and stores it as resume_guess. It is safe to call more than once.
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) Reach ¶ added in v2.4.0
func (m *Manager) Reach(targetID int64) TargetReach
Reach reports a target's reachability as the poller last saw it. A poll that has been running longer than UnreachableAfter already counts as unreachable.
func (*Manager) RecoverWorkspaceOperation ¶
func (*Manager) RecoverWorkspaceOperations ¶
func (*Manager) RecoverWorktree ¶
func (*Manager) Relaunch ¶ added in v2.4.0
Relaunch starts an interrupted session again in its own record, the way restart recovery does: with its saved conversation when one is bound, otherwise fresh, typed prime first when given. It is for rows a restart left "interrupted" — automatic recovery either had no conversation to resume or failed to launch.
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) ReopenShell ¶ added in v2.4.0
ReopenShell starts a new tracked shell in a closed shell's folder, with its name, project and group. A shell has no conversation to resume; its scrollback went with the old terminal.
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) Retire ¶ added in v2.4.0
Retire ends an interrupted row whose terminal is gone, so a replacement can take over its work. Rows that are already ended are left as they are.
func (*Manager) SendKey ¶
SendKey presses one allowlisted key in a session — Escape to interrupt a turn, Enter to accept, and so on.
func (*Manager) SendNotice ¶ added in v2.4.0
SendNotice types a machine-originated message (a CI failure report, say) into a session. Unlike SendText it adds no recalled memory context: the message is not the operator's prompt, so recall keyed on it is noise.
func (*Manager) SendNudge ¶ added in v2.4.0
SendNudge types text into a session exactly as given, without the automatic memory context SendText prepends: the usage-limit resume (internal/limits) must be able to find its own words in the pane.
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) SetAgentProbeInterval ¶ added in v2.4.0
SetAgentProbeInterval changes how often the agent probe may run per target; tests shorten it.
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) StartLimitHandoff ¶ added in v2.4.0
StartLimitHandoff moves a session stopped by its usage limit to another agent or model in the same workspace. The limited agent cannot write a handoff, so runHandoff builds one from what Lectern captured (limitWrap). The original session is kept; its hold is resolved once the successor runs.
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) SwapAccount ¶ added in v2.6.0
SwapAccount restarts a session's agent under another account and resumes its conversation there. committed is true once the agent runs under the new account (the session row names it); err after a commit means the resumed agent did not show a prompt within the wait, or exited (ErrAgentExited).
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 NativeCandidate ¶ added in v2.4.0
NativeCandidate is one saved conversation in a folder.
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 SessionsSpec ¶ added in v2.6.0
type SessionsSpec struct {
Command string `json:"command,omitempty"`
Files []string `json:"files,omitempty"`
Header string `json:"header,omitempty"`
Whole bool `json:"whole,omitempty"`
SQLite []string `json:"sqlite,omitempty"`
Query string `json:"query,omitempty"`
ID string `json:"id"`
Dir string `json:"dir,omitempty"`
Created string `json:"created"`
Updated string `json:"updated,omitempty"`
Title string `json:"title,omitempty"`
}
SessionsSpec is one way to list a CLI's saved conversations (internal/nativeidentity/catalog_sessions.py reads it on the target). Exactly one source is set:
- Command prints JSON (an array, or one object per line), run in the working directory; {bin} is the resolved binary.
- Files are glob candidates for session files; the first whose $VARS are all set is used. {slug} is the workspace path with every non-alphanumeric character replaced by "-". Header keeps only lines whose "type" matches; Whole reads each file as one JSON document instead of JSON lines.
- SQLite are candidate database paths (first with its $VARS set), read with Query.
ID, Dir, Created, Updated and Title name the fields (dot paths); ID "@stem" is the file name without its extension. Dir is compared with the workspace; leave it empty only when the listing is already scoped to the working directory. Created/Updated accept epoch seconds, milliseconds or ISO-8601.
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"`
// SessionIDArgs name a NEW conversation at launch, with {id} replaced by a
// UUID Lectern generates and records on the session, e.g.
// ["--session-id", "{id}"]. With it, Restore, Recent and Switch can resume
// exactly that conversation later without ever reading the CLI's storage.
SessionIDArgs []string `json:"session_id_args,omitempty"`
// ForkSessionID says SessionIDArgs may also name a fork's new
// conversation (claude-style --resume X --fork-session --session-id Y).
ForkSessionID bool `json:"fork_session_id,omitempty"`
// Sessions says where the CLI lists its saved conversations, so a session
// Lectern could not name at launch still gets its id bound afterwards, and
// an id is checked against the workspace before it is resumed or forked.
Sessions *SessionsSpec `json:"sessions,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"`
// PromptArgs pass the opening message through arguments instead, with
// {prompt} replaced by the message, e.g. ["--prompt", "{prompt}"] or
// ["-i", "{prompt}"] for a CLI whose bare positional would run one-shot
// and exit, or ["--", "{prompt}"] where a positional must be separated
// from options. It takes precedence over PromptArg.
PromptArgs []string `json:"prompt_args,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"`
// YoloEnv is the same switch for a CLI that only reads it from the
// environment (goose's GOOSE_MODE=auto). Like YoloArgs it is applied only
// when the launch asks for yolo, never as agent-wide Env.
YoloEnv map[string]string `json:"yolo_env,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"`
// ACP, when set, makes a background task on this agent run through
// internal/drivers' ACP client driver (Agent Client Protocol,
// agentclientprotocol.com) instead of the generic Task invocation above —
// Task and ACP are mutually exclusive ways to give an agent a
// non-interactive capability, and ACP is picked automatically whenever
// it is set (see internal/drivers.KindACP, internal/agents.ACPDefinition).
// It gets a configured CLI the same live timeline, mid-run steering and
// gated approvals codex-appserver already gives codex, with no per-CLI
// backend code: any binary that speaks ACP on stdio qualifies. Presets
// for Zed's claude-code-acp/codex-acp adapters and Gemini CLI's
// --experimental-acp are offered in Settings → Agents but are not
// pre-registered here — see docs/acp.md.
ACP *ACPSpec `json:"acp,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) AssignsSessionID ¶ added in v2.6.0
AssignsSessionID reports whether a launch with these options names its new conversation itself: a fresh launch, or a fork when the CLI allows it.
func (Spec) Capabilities ¶ added in v2.4.0
func (s Spec) Capabilities() map[Capability]CapabilityState
Capabilities reports, for every capability a picker might offer, whether this spec supports it — driven almost entirely by which registry fields are populated, so a capability degrades the moment the corresponding field is empty rather than needing separate bookkeeping. Task and ACP being mutually exclusive non-interactive backends (see ACPSpec's doc comment) means CapTask and CapACP can never both report Available for a non-builtin spec, but a picker offering "background work" only needs to check whether either is true.
CapTask is the one exception to "driven by fields": a built-in is always task-capable even with neither field set, because claude and codex get their non-interactive backend from Go code (hook.py's gate, the codex-appserver driver — see taskPermissionError in internal/api) rather than from Spec.Task/Spec.ACP, exactly as internal/api's taskAgent already treats Builtin as sufficient on its own.
func (Spec) ExactConversations ¶ added in v2.6.0
ExactConversations reports whether Lectern can bind this agent's sessions to an exact conversation id: the built-ins by process evidence, a catalog agent by naming it at launch or by reading where the CLI lists them.
func (Spec) Installed ¶ added in v2.4.0
Installed reports whether this spec's own binary resolves on PATH for wherever this process runs — there is no per-target remote exec path in this codebase (yet) to check instead, so "the lectern host" is the only answer this can give. A Task or ACP backend that shells out to a different binary (e.g. npx) is not checked here.
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) TakesPrompt ¶ added in v2.6.0
TakesPrompt reports whether the opening message can ride on the command line (PromptArg or PromptArgs); otherwise it is typed once the pane settles.
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
// SessionID names the new conversation through SessionIDArgs; set only
// when AssignsSessionID is true.
SessionID 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
// Isolation runs the agent inside a bwrap/docker sandbox instead of
// directly on the target — see internal/isolation. The zero value keeps
// today's unsandboxed behavior.
Isolation isolation.Config
// IsolationOpts carries what Isolation needs beyond the fields above
// (the proxy socket for network=deny). Ignored when Isolation is none.
IsolationOpts isolation.WrapOpts
}
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 TargetReach ¶ added in v2.4.0
type TargetReach struct {
Unreachable bool `json:"unreachable"`
Since float64 `json:"since,omitempty"` // unix seconds the problem started
Error string `json:"error,omitempty"`
}
TargetReach is what the session list shows about a target's reachability.
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
¶
- account_swap.go
- adopt.go
- adopted_match.go
- agent_exit.go
- agents.go
- archive.go
- background_launch.go
- boot.go
- catalog.go
- catalog_conversations.go
- checkpoint_manifest.go
- claude_fork_path.go
- codex_usage_poll.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
- reach.go
- recovery.go
- reopen.go
- restore.go
- resume.go
- sessions.go
- setup_cancel.go
- setup_recovery.go
- stop.go
- takeover.go
- terminal_mouse.go
- trust_compat.go
- workspace_lifecycle.go
- workspace_operations.go