terminal

package
v0.93.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 67 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package terminal spawns PTY-backed shell sessions and bridges their I/O to the window over the local WebSocket transport (transport.go), falling back to the /events channel. Sessions are keyed by an opaque session ID and run independently of the window, so navigating away from a project (or hiding its terminal) never kills its shell. A project may own several sessions.

Index

Constants

View Source
const KindService = "service"

KindService marks a PTY that runs a project service's command (internal/services) instead of a session: it has no row, no provider and no hooks, and it is not counted as a session anywhere.

View Source
const KindShell = "shell"

KindShell marks a session that runs the user's shell instead of a provider.

Variables

View Source
var ErrChatView = errors.New("this session is drawn as a chat; switch it to the terminal first")

ErrChatView refuses a terminal spawn for a session drawn as a chat.

Functions

func AddToShellRC

func AddToShellRC(shell, home, dir string) (string, error)

AddToShellRC puts dir on the PATH of the user's shell, in the startup file that shell reads, so the binary an installer left there answers in any terminal and in the login shell lich resolves its PATH from at the next launch. A file that already names dir is left alone. It returns the file it wrote, "" when it had nothing to do.

func ClaudeTranscript

func ClaudeTranscript(id string) (string, bool)

ClaudeTranscript is where Claude Code keeps conversation id, found under every profile.

func Conversations

func Conversations() []store.Conversation

Conversations lists every conversation the providers keep on disk, whoever started it (store.SetConversationsOf). Headless runs and sub-agents are left out: neither is a conversation somebody resumes by hand.

func PinPath

func PinPath(env []string)

PinPath copies env's PATH into lich's own process. ResolveShellEnv's merge only reaches what lich hands a child as cmd.Env, and that is not what resolves a bare binary name: exec.LookPath — and exec.Command, which calls it — reads the process PATH, never cmd.Env. So a GUI launch that never sourced the rc files fails to find anything the rc files put on PATH: provider detection reports codex missing and the spawn cannot start it. macOS is where this bites hardest — a Finder-launched .app gets launchd's bare PATH, without Homebrew's prefix — but a .desktop launch is the same shape.

func ReresolveShellEnv

func ReresolveShellEnv(base []string) ([]string, error)

ReresolveShellEnv is ResolveShellEnv with the failure returned rather than logged, and it is what a user-pressed re-check runs (internal/providers.Service.RefreshPath). Boot has nowhere to show a failure and carries on with the launch env; a re-check does, and must not hand back a re-scan of the PATH lich booted with as if it were fresh.

The bound is the same one boot pays (shellEnvTimeout and the end marker in runShellDump), so a login shell sitting on a prompt costs the button what it costs a launch, and no more.

func ResolveShellEnv

func ResolveShellEnv(base []string) []string

ResolveShellEnv augments base with the variables a login+interactive shell exports. lich is launched from a GUI, so its environment is the graphical session's — it never sourced .zshrc/.bashrc/config.fish/.profile, where users commonly export things like an MCP server's auth token. A "shell" session hides this because the shell we spawn sources those rc files itself; a provider spawned directly (claude/codex/...) does not, so its ${VAR} expansions in .mcp.json come up empty. We run the user's shell the way a terminal emulator does — attached to a pty, see runShellDump — and merge its environment over base.

SHELL unset (normal Windows: cmd.exe has no rc) or any failure returns base unchanged — the resolution is best-effort, never load-bearing.

func SupportsEffort

func SupportsEffort(kind string) bool

SupportsEffort reports whether a provider can be told a reasoning effort when lich spawns it, which is what rejects one SupportsModel's way.

func SupportsModel

func SupportsModel(kind string) bool

SupportsModel reports whether a provider can be told which model to run when lich spawns it. It is what rejects `--model` for a kind that would silently drop it, so the caller hears about it instead of getting a session on the wrong model.

func SupportsUltracode

func SupportsUltracode(kind string) bool

SupportsUltracode reports whether a provider has an ultracode to turn on. Claude Code is the only one.

func TranscriptText

func TranscriptText(providerSessionID, cwd string) (text string, cut bool)

TranscriptText is one conversation as a single block of searchable prose: every message either side of it said, oldest first, with the tool calls and results between them left out. It is what the history index stores for a parked session, and it is read through exactly the two mechanisms the live search is (search.go): a walk by the provider's own line reader, or a query for the two providers that keep their messages in a database of their own.

cut reports that indexTextBytes dropped the oldest of it, which is what a history row shows under its snippet: an index that does not go all the way back has to say so where the search that missed is read.

cwd is the directory the session ran in, needed by Crush and Cursor alone. Empty for every miss: a provider lich can read by neither mechanism, a transcript that is gone, a conversation id nothing on disk matches. A caller records the empty answer the way it records a full one, and that is what marks the session indexed and keeps a backfill from asking again every time.

func WithPathDir

func WithPathDir(env []string, dir string) []string

WithPathDir is env with dir ahead on its PATH, unless PATH already holds it: the folder an installer wrote a provider into, which lich resolves binaries through and hands its sessions from then on.

Types

type ChatBirth

type ChatBirth struct {
	Model, Effort string
	AutoApprove   bool
}

ChatBirth is what a chat's argv could not carry, for the protocol to set: the model and effort the session was born on, empty on a resume (a birth value, modelArgs), and whether every permission is answered yes, which is the checkout's skip-permissions setting.

type ChatLaunch

type ChatLaunch struct {
	Model       string
	AllowBypass bool
	// Server is what opencode's own HTTP server listens with, which the chat
	// answers the agent's questions through: opencode hands its question tool
	// to no ACP client.
	Server *OpenCodeServer
}

ChatLaunch is what a chat's process has to be started with for a setting its protocol cannot change in flight: Claude Code's bypassPermissions, which needs AllowBypass, and Kiro's model, whose session/set_model never answers and leaves the model as it was (measured on 2.21.0) while `acp --model` holds on a session/load. Model is passed on a resume too, unlike a birth model: it is the person's choice of a moment ago.

type ChatProcess

type ChatProcess struct {
	Stdin  io.WriteCloser
	Stdout io.ReadCloser
	Birth  ChatBirth
	// ProfileDir is the profile's config directory the process runs in, ""
	// for Personal's.
	ProfileDir string
	// contains filtered or unexported fields
}

ChatProcess is a session's provider running as a chat: Stdin and Stdout carry the protocol.

func (*ChatProcess) Close

func (p *ChatProcess) Close()

Close ends the process the way every protocol is told to end, by closing its stdin, and kills it if it has not left within chatCloseGrace. It returns once the process is gone.

func (*ChatProcess) Command

func (p *ChatProcess) Command(ctx context.Context, args ...string) (*exec.Cmd, error)

Command is the provider's CLI run with args in the chat's directory and environment, outside the sandbox: for what its protocol has no request for.

func (*ChatProcess) Done

func (p *ChatProcess) Done() <-chan struct{}

Done closes once the process has exited.

func (*ChatProcess) Stderr

func (p *ChatProcess) Stderr() string

Stderr is the end of what the process wrote to stderr, which is what says why one that died did.

type ChatSink

type ChatSink interface {
	// Opened is whether session id's chat has opened its conversation, before
	// which a message would land mid-handshake.
	Opened(id string) bool
	// Take sends text as session id's next message, at once or after the turn
	// running, and waits on that turn's start.
	Take(id, text string) (relay.HandedPrompt, error)
	// LastAnswer is the final message of session id's last turn, "" when that
	// turn wrote none.
	LastAnswer(id string) string
	// BackgroundWork is whether session id's agent has work of its own
	// running in the background, where its protocol says so.
	BackgroundWork(id string) bool
}

ChatSink is the chat service (internal/chat) as the relay reaches a session drawn as a chat: its process has no terminal to type at, so a prompt goes to the chat as its next message.

type ChatUsage

type ChatUsage struct {
	Conversation string
	Window       int
	CostUSD      *float64
	RateLimits   []quota.ReportedLimit
}

ChatUsage is what a Claude Code chat's stream-json says about its own conversation: the context window its model runs with, the conversation's whole cost so far, and the account's rate limits. Window and CostUSD belong to Conversation and are applied to no other; a report without one carries rate limits alone. Zero and nil mean not said.

type LastSaid

type LastSaid = api.LastSaid

type OpenCodeServer

type OpenCodeServer struct {
	Port     int
	Password string
}

OpenCodeServer is the port and the password of the HTTP server `opencode acp` runs beside the protocol, and the variables that switch on its question tool and its basic auth (measured on 1.19.4: the tool is left out of an ACP session unless OPENCODE_ENABLE_QUESTION_TOOL is set, and without OPENCODE_SERVER_PASSWORD the server answers anyone on the machine).

type Service

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

Service manages PTY-backed shell sessions keyed by session ID.

func New

func New(store Store, env []string, hub *events.Hub) *Service

New returns a ready-to-use terminal service that resolves the binary to spawn through store. env is the process environment to derive session environments from — callers pass a snapshot taken before any os.Setenv tweaks (main.go forces GDK_BACKEND on Linux) so those never leak into spawned shells. hub receives every app event the service pushes to the UI.

func (*Service) AgentName

func (s *Service) AgentName(id string) string

AgentName is the name this session's agent answers to in its provider's peer roster right now — the one lich passed at spawn, or whatever a `/rename` typed inside the session changed it to. Empty when there is nothing on record, which is what leaves the caller with lich's own derived name (relay.RosterNameOf).

Claude Code is the only provider read here, and the only one that has anything to read: it is the only one lich names at spawn (command.go, nameArgs) and the only one whose sessions can rename themselves. Codex, Antigravity, opencode, oh-my-pi, Crush, Cursor CLI and Kiro CLI are never handed a roster name at all — the name lich addresses their sessions by is lich's own, it never crosses into the harness, and there is no `/rename` in any of them for it to fall out of step with.

The read is the transcript rather than the `sessions/<pid>.json` Claude Code keeps beside it, which is one small file against a bounded tail of a large one. That file is keyed by the pid of the `claude` process, and a confined session's runs in a PID namespace of its own (internal/sandbox, --unshare-pid) whose numbers lich does not share — so the sessions most in need of the read are the ones it could not name. The transcript is the same file for both, and the one this package already resolves for cost and for the last-turn recap.

func (*Service) AtPrompt

func (s *Service) AtPrompt(id string) bool

AtPrompt is Ready without the draft check: whether the provider is the program reading this PTY and sitting at its prompt, whoever has typed there. It is the question for a write that does not send — text pasted for the person to finish and submit themselves — where a half-written line is the place the text belongs rather than a reason to hold it back.

func (*Service) BackgroundWork

func (s *Service) BackgroundWork(id string) bool

BackgroundWork is whether session id's agent ended its last turn with work still running in the background (relay.Terminal): its chat's driver says so, and in a terminal its last `done` report did.

func (*Service) BindConversation

func (s *Service) BindConversation(id, providerSessionID string) error

BindConversation records the conversation session id's chat runs, which is what its terminal resumes.

func (*Service) Chat

func (s *Service) Chat(id string) bool

Chat is whether session id is drawn as a chat (relay.Terminal).

func (*Service) ChatOpened

func (s *Service) ChatOpened(id string) bool

ChatOpened is whether session id's chat has opened its conversation (relay.Terminal), before which a message would land mid-handshake.

func (*Service) ChatPrompt

func (s *Service) ChatPrompt(id, text string) (relay.HandedPrompt, error)

ChatPrompt hands text to session id's chat as its next message (relay.Terminal): relay.ErrNoChat for a session not drawn as one.

func (*Service) Close

func (s *Service) Close(_ context.Context, opts api.SessionIDOptions) (api.None, error)

Close terminates a session's shell, if any. It is the window's close, so no session is named as the one that asked for it.

func (*Service) CloseBy

func (s *Service) CloseBy(id, closerID string) error

CloseBy is Close on behalf of closerID, the session that asked for it.

func (*Service) CloseTransport added in v0.86.0

func (s *Service) CloseTransport() error

CloseTransport frees the loopback port for the next lich, before the slow part of quitting. No-op when the transport failed to start.

func (*Service) CodexHookChecked

func (s *Service) CodexHookChecked() bool

CodexHookChecked is whether a Codex session already read whether Codex runs lich-plugin's PreToolUse hook: the check runs once per lich run.

func (*Service) CodexProfileSessions

func (s *Service) CodexProfileSessions(slug string) int

CodexProfileSessions is ProfileSessions for a Codex profile.

func (*Service) ContinueIn

func (s *Service) ContinueIn(ctx context.Context, opts api.ContinueInOptions) (api.None, error)

ContinueIn moves a session's conversation to another profile of the same provider and carries on there, in the same card: the process ends, the conversation and everything its provider keyed by its id move (claudeprofile.MoveConversation and its siblings; a Kiro CLI conversation is every profile's and stays, an opencode one cannot move), the row takes the new profile, and a running session is spawned again resuming it. Moving back is the same call. Nothing else moves: not the other sessions in the profile, and not the project's own profile. A session that has its id but no transcript yet, before its first prompt, has nothing to move: it starts afresh in the target profile.

It refuses a turn in progress: a provider-reported turn still open, which a permission prompt is part of. A turn a usage limit stopped has ended, so a session waiting out its limit moves like an idle one.

func (*Service) FinalMessage

func (s *Service) FinalMessage(id string) (string, bool)

FinalMessage is the final message of session id's last turn, whole, and whether lich can read one for it (relay.Terminal): a chat's driver has it; in a terminal it is the last-turn recap's reading, uncut, for every provider whose conversation lich reads (transcriptReaderFor, sessionDBTexts), which leaves Cursor CLI out.

func (*Service) FlushHandsOn

func (s *Service) FlushHandsOn()

FlushHandsOn writes what every session has been worked since the last write. Called off the debounce, when a card closes and once on the way out, so a session's hours outlive the process that counted them.

func (*Service) HandsOn

func (s *Service) HandsOn(_ context.Context, opts api.SessionIDOptions) (int64, error)

HandsOn is how long session opts.ID has been worked on, in whole seconds: the time it was reporting, being typed at or producing output for an open turn, minus every silence longer than handsOnIdleGap (see handsOn). Zero for a session nothing has been counted for yet, and up to handsOnFlush behind what has actually been measured — the readout is in minutes, so the debounce never shows.

func (*Service) HoldInput

func (s *Service) HoldInput(id string) func()

HoldInput keeps the person at this session's keyboard out of a submission that is not theirs, and returns the release that hands their keystrokes back.

A relayed delivery is two writes a beat apart — the paste, then the Enter that sends it (internal/relay, typeIn) — and everything typed in between lands on the same line and is submitted as part of the relayed message. Unlike a delivery that waits out a draft, this is not an omission: it is the user's own text going somewhere they never sent it, and the window is theirs to lose from the moment the paste lands until the target's PTY goes quiet.

So the keystrokes are held rather than dropped, and written the moment the Enter is gone: they land on the fresh prompt the relayed message left behind, which is where the user was typing them. Unknown sessions hand back a release that does nothing.

Holds count rather than latch, because two senders can deliver into one target at the same time and the first Enter through must not hand the second delivery's window back to the keyboard. Each release is to be called once.

func (*Service) InterruptService added in v0.79.0

func (s *Service) InterruptService(id string) error

InterruptService types Ctrl+C at service id's console, the way the user would: the command is asked to stop and decides how long that takes. A service that is not running is a no-op.

func (*Service) KillService added in v0.79.0

func (s *Service) KillService(id string)

KillService ends service id's process without waiting for it to agree: SIGTERM, then SIGKILL past closeGrace (ptyHandle.Close). It returns at once; the exit reaches ServiceCommand.Exited like any other. A service that is not running is a no-op.

func (*Service) LastTurnSaid

func (s *Service) LastTurnSaid(_ context.Context, opts api.SessionIDOptions) (LastSaid, error)

LastTurnSaid returns the last thing the agent said in this session's conversation, as plain text.

It answers the half of "what happened while I was away" that a diff cannot: a turn that ran the suite and reported three failures changed nothing on disk, and that is exactly the turn worth catching up on. Nothing here summarises anything — the agent wrote this sentence itself, and lich only finds it.

It is the last message on record, not the last message of the current turn: the two agree once a turn has finished, and mid-turn this is still the previous turn's words.

func (*Service) Live

func (s *Service) Live(_ context.Context, opts api.SessionIDOptions) (bool, error)

Live answers live over RPC.

func (*Service) LiveCount

func (s *Service) LiveCount(_ context.Context, _ api.None) (int, error)

LiveCount answers liveCount over RPC.

func (*Service) Mount

func (s *Service) Mount(pattern string, handler http.Handler)

Mount exposes an extra handler (the RPC dispatcher, the events push socket) on the transport listener, behind its token. No-op when the transport failed to start — those surfaces then simply don't exist, like /ws.

func (*Service) OMPProfileSessions

func (s *Service) OMPProfileSessions(slug string) int

OMPProfileSessions is ProfileSessions for an oh-my-pi profile.

func (*Service) ProfileSessions

func (s *Service) ProfileSessions(slug string) int

ProfileSessions counts the live sessions running in a Claude Code profile, so a profile is never deleted out from under one.

func (*Service) QuietFor

func (s *Service) QuietFor(id string) time.Duration

QuietFor reports how long a session's PTY has produced nothing, which is the only way from outside to tell that the program on the other end has finished taking in what was typed at it. A session that has never written a byte — and one nobody knows — is as quiet as a session gets.

Ready answers a coarser version of the same question once, and latches; this one is asked again in the middle of a delivery, where the quiet that matters is the one happening right now (internal/relay, awaitSettled).

func (*Service) Reachable

func (s *Service) Reachable(_ context.Context, opts api.SessionIDOptions) (bool, error)

Reachable answers whether session id has a process a message can reach: its terminal, or its chat. Live stays the terminal's question, since a write that needs the PTY must not be told a chat is there to take it.

func (*Service) Ready

func (s *Service) Ready(_ context.Context, opts api.SessionIDOptions) (bool, error)

Ready answers ready over RPC, and for a chat whether it has opened its conversation: a chat takes a message during a turn too, queued behind it.

func (*Service) Replay

func (s *Service) Replay(_ context.Context, opts api.SessionIDOptions) (bool, error)

Replay queues the capped tail of a session's PTY output on /ws as a replay frame, so a window attaching to a running session can reseed a fresh terminal's scrollback: the output frames before it are in the tail, and the ones after it are not. It reports whether a replay frame is coming, false for an unknown session, which a brand-new one is: it has no history yet.

func (*Service) ReportChatState

func (s *Service) ReportChatState(id, state, tool, detail string)

ReportChatState is a chat's own state report, read the way a hook's is: the card's ring, the unread mark, the relay's watch and the readouts taken off the transcript all follow it. A chat reports for itself, so the hooks its provider still fires are dropped (onHookState).

func (*Service) ReportChatUsage

func (s *Service) ReportChatUsage(id string, u ChatUsage)

ReportChatUsage keeps a chat's figures for the footer's readout, passes its rate limits on to the plan gauge and pushes the readout again.

func (*Service) ReportCodexHook

func (s *Service) ReportCodexHook(id, trust string)

ReportCodexHook files the first hook check's answer, trust being lich's PreToolUse hook's status when Codex skips it and "" when it runs, and tells the window when it is skipped. Later reports are dropped.

func (*Service) Resize

func (s *Service) Resize(_ context.Context, opts api.ResizeOptions) (api.None, error)

Resize updates a session's PTY window size. The window only calls this for the visible terminal; a hidden terminal is resized on the next time it is shown.

func (*Service) Resumable

func (s *Service) Resumable(kind, providerSessionID, cwd string) bool

Resumable reports whether conversation providerSessionID of a kind session can still be reopened (resumeAvailable).

func (*Service) ResumeAvailable

func (s *Service) ResumeAvailable(_ context.Context, opts api.ResumeAvailableOptions) (bool, error)

ResumeAvailable answers resumeAvailable over RPC.

func (*Service) RunLimitWatch

func (s *Service) RunLimitWatch()

RunLimitWatch checks every open Codex turn for having ended on a usage limit, until the process ends. Started once at launch: with no Codex turn open, a pass costs one look at the turn log.

func (*Service) SearchTranscripts

func (s *Service) SearchTranscripts(_ context.Context, opts api.SearchTranscriptsOptions) ([]TranscriptMatch, error)

SearchTranscripts answers searchTranscripts over RPC.

func (*Service) ServiceOutput added in v0.84.0

func (s *Service) ServiceOutput(id string) []byte

ServiceOutput is what service id has printed so far, capped like a session's replay tail; nil when it is not running.

func (*Service) SessionAccount

func (s *Service) SessionAccount(id string) (env map[string]string, read bool)

SessionAccount reports what a session says about the account its provider spends: the environment of the process running in its PTY, and whether that environment could be read at all.

It exists for the quota reader (internal/quota), which asks it before deciding which login to measure. read is false for a session with no live process as well as for a platform that exposes no environment (env_other.go), and a reading is withheld rather than taken against the machine-wide login lich happens to see.

Not routed over /rpc/ (internal/routes): the environment it returns carries that session's own credentials.

func (*Service) SessionCheckout added in v0.82.0

func (s *Service) SessionCheckout(id string) (dir string, port int)

SessionCheckout is the directory a live session was spawned in and the dev-server port that checkout reserves, or zero values once it is gone or never held one.

func (*Service) SetArtifactDir added in v0.88.0

func (s *Service) SetArtifactDir(dir string)

SetArtifactDir names the directory holding every session's artifacts (internal/artifact). Each spawn gets its own subdirectory, created then and named in its environment, and bound writable when the session is confined.

Startup wiring, called before anything spawns.

func (*Service) SetCardClosed added in v0.82.0

func (s *Service) SetCardClosed(fn func(id string))

SetCardClosed wires fn to every card Close takes down, after its process is gone. Unlike SetSessionClosed, a process ContinueIn ends and spawns again under the same card is not one.

func (*Service) SetChat

func (s *Service) SetChat(c ChatSink)

SetChat wires the chat service the relay's prompts reach a chat through.

func (*Service) SetDropDir

func (s *Service) SetDropDir(dir string)

SetDropDir names the directory holding the copies of dropped files (internal/drop). A confined session binds its own subdirectory of it at spawn — the copy is written by lich, outside the sandbox, so without the bind the path pasted at the prompt names a file the session cannot open.

Startup wiring, called before anything spawns.

func (*Service) SetEditNotes

func (s *Service) SetEditNotes(fn func(api.TouchedRequest) string)

SetEditNotes wires what answers a touch with its edit-overlap note: internal/relay's Touched. Startup wiring, before any session runs; with none every touch answers 204.

func (*Service) SetEnv

func (s *Service) SetEnv(env []string)

SetEnv replaces what a session spawned from now on inherits, after a re-read of the login shell replaced the environment lich booted with (internal/providers.Service.RefreshPath). A session already running keeps the environment it was born with: its PTY was handed a copy at spawn, and there is no way to reach into a live process's environment anyway.

func (*Service) SetPromptLanguage

func (s *Service) SetPromptLanguage(lang func() prompt.Lang)

SetPromptLanguage wires where a spawn reads the language of the text lich hands it: the briefing on its command line, and prompt.EnvVar for whatever composes text inside the session. Read at every spawn, so a change in Settings reaches the sessions started after it. Without it every spawn is English, the default. Called at startup, before any session spawns.

func (*Service) SetQuotaLeft added in v0.87.0

func (s *Service) SetQuotaLeft(fn func(kind, slug string) bool)

SetQuotaLeft wires the answer to "can this profile of this provider take a turn now" (quota.Service.HasQuotaLeft). Unset, nothing is ever offered.

func (*Service) SetRateLimitReports

func (s *Service) SetRateLimitReports(fn func(sessionID string, limits []quota.ReportedLimit))

SetRateLimitReports wires where the rate limits a session reports go: the plan gauge's reader. Startup wiring, called once before any session reports.

func (*Service) SetRestart

func (s *Service) SetRestart(fn func() error)

SetRestart wires the POST /restart endpoint to fn, the in-place relaunch the update flow triggers after replacing the binary. No-op when the transport failed to start — /restart then simply reports unavailable.

func (*Service) SetResumeNow added in v0.87.0

func (s *Service) SetResumeNow(fn func(id string))

SetResumeNow wires the continuation sent once the person moved a session off its limit (relay.ResumeNow).

func (*Service) SetSessionClosed

func (s *Service) SetSessionClosed(fn func(id, closerID string))

SetSessionClosed wires fn to every session Close or ContinueIn takes down, called before its process is killed with the session that closed it (CloseBy), empty for a close the window made. Only one watcher, the relay (relay.SessionClosed).

func (*Service) SetSessionExited

func (s *Service) SetSessionExited(fn func(id string))

SetSessionExited wires fn to every session whose process ended on its own, called once lich has reaped it. Only one watcher, the relay (relay.SessionExited).

func (*Service) SetSessionState

func (s *Service) SetSessionState(fn func(id, state string))

SetSessionState wires fn to every session-state report the hooks deliver. Only one watcher: the relay is the only thing that needs the stream, and the window gets the same reports over its own event channel.

func (*Service) SetShellIntegrationDir

func (s *Service) SetShellIntegrationDir(dir string)

SetShellIntegrationDir names the directory shellintegration.Install wrote the shell scripts to; "" leaves shell sessions without them.

Startup wiring, called before anything spawns.

func (*Service) SetStartReports

func (s *Service) SetStartReports(installed func(provider string) bool)

SetStartReports wires the question of whether a provider's sessions run lich's hooks at all. Without them no session-start ever arrives, so a session of that provider is not held back waiting for one (see Ready).

func (*Service) SetSubagent

func (s *Service) SetSubagent(fn func(context.Context, api.SubagentRequest) (api.SubagentAnswer, func(written bool)))

SetSubagent wires what answers /subagent: internal/subagent's Decide. Startup wiring, before any session runs; with none every call is allowed.

func (*Service) SetToolUse added in v0.87.0

func (s *Service) SetToolUse(fn func(id, tool, detail string))

SetToolUse wires fn to the tool every PreToolUse report names. Only one watcher, the relay.

func (*Service) SetUsageLimit

func (s *Service) SetUsageLimit(fn func(id string, resetsAt int64))

SetUsageLimit wires fn to every turn a usage limit ended that names its reset (relay.ParkResume). Only one watcher, like SetSessionState.

func (*Service) SetUserTyped added in v0.87.0

func (s *Service) SetUserTyped(fn func(id string))

SetUserTyped wires fn to every line a person sends at a session's prompt from the window. Only one watcher, the relay.

func (*Service) SetVisible

func (s *Service) SetVisible(_ context.Context, opts api.SetVisibleOptions) (api.None, error)

SetVisible tells the session's output coalescer whether its terminal is on screen. Hidden sessions batch output (~250ms per event); flipping to visible flushes pending output immediately. Unknown sessions are a no-op.

func (*Service) Start

func (s *Service) Start(_ context.Context, opts api.StartOptions) (api.None, error)

Start spawns the binary for session opts.ID under project opts.ProjectID — the user's shell when opts.Kind is "shell", otherwise the provider binary for that kind resolved from the project's settings (falling back to the provider's default on $PATH) — attached to a new PTY sized to opts.Cols x opts.Rows and rooted at opts.Cwd, then streams its output to the window. An empty opts.Cwd defaults to the user's home directory. Starting a session that is already running is a no-op.

A non-empty opts.Resume is a provider conversation id to reopen, spelled for the session's kind by resumeArgs, which the window passes after the user accepted the prompt to continue the session this card ran before the last restart. The prompt is only raised for a conversation ResumeAvailable still finds, so an id the provider no longer knows normally never reaches here; one that slips through (pruned between the check and the spawn) fails in the PTY like any other bad invocation — the user sees the provider's own error.

opts.Fork turns that resume into a branch: the provider copies the conversation into a new one of its own and leaves the original alone, so the card that ran it stays where it is with its history intact. Only the three kinds providers.SupportsFork names can do it, and only alongside a resume id — the conversation being branched is the one that id points at. The copy's own id is the provider's to assign, and reaches lich through this session's session-start report like any other.

The name the session answers to in its provider's peer roster (Claude Code's `/list-agents`, the only provider with one) is a name already on record for this session (AgentName): a restart opens a conversation of its own, and a `/rename` typed in the last one is a decision the user made about this card rather than about that conversation. A fork with nothing on record is named by lich (nameArgs); any other session is left to name itself.

func (*Service) StartChat

func (s *Service) StartChat(_ context.Context, opts api.StartOptions, launch ChatLaunch) (*ChatProcess, error)

StartChat spawns session opts.ID's provider as a chat, rooted where its terminal would be and with everything its terminal would carry, plus what launch adds. Refused while the session's terminal runs.

func (*Service) StartService added in v0.79.0

func (s *Service) StartService(c ServiceCommand) error

StartService runs c.Line in the user's shell on a new PTY registered under c.ID, which the window reaches through the same Write, Resize, Replay and SetVisible a session's terminal takes. The command runs on its own: no rc file is loaded and no shell is left behind it, so its exit is the service's exit. Starting an id already running is an error.

func (*Service) Status added in v0.82.0

func (s *Service) Status(id string) api.SessionStatus

Status is the last session-status report the window was sent for a session, zero when there is none.

func (*Service) StopTerminal

func (s *Service) StopTerminal(id string) error

StopTerminal ends session id's terminal the way a close does, keeping the session, and returns once its child has been reaped. A session with no terminal running is left alone.

func (*Service) SuggestProfile added in v0.87.0

func (s *Service) SuggestProfile(id, slug string) error

SuggestProfile holds the profile an agent handing off suggested for its successor, for the person once a turn has ended there (showHeldOffer). It moves nothing. The error is why the suggestion cannot apply, which the handoff reports and does not fail over.

func (*Service) TakeProfileOffer added in v0.87.0

func (s *Service) TakeProfileOffer(ctx context.Context, opts api.ContinueInOptions) (api.None, error)

TakeProfileOffer is the person taking the profile a session was offered: the session moves through Continue in and, off a limit, its continuation goes out at once. An offer no longer standing is refused: the turn that moved on, the card that closed or moved since took it down. A successor mid-turn is refused by Continue in itself and says so. Its offer goes back to held rather than being spent, so it is shown again when that turn ends: the click took the toast down.

func (*Service) Transport

func (s *Service) Transport() TransportInfo

Transport returns the WebSocket endpoint for terminal I/O.

func (*Service) TransportError

func (s *Service) TransportError() error

TransportError reports why the transport is absent, nil when it started. It stays out of TransportInfo on purpose: the window has no use for an OS error, and the launch-failure log is the only caller.

func (*Service) TurnOpen

func (s *Service) TurnOpen(id string) bool

TurnOpen reports whether session id is in the middle of a turn.

func (*Service) TurnStates

func (s *Service) TurnStates(_ context.Context, _ api.None) ([]TurnState, error)

TurnStates answers turnStates over RPC.

func (*Service) WorkdirMissing

func (s *Service) WorkdirMissing(_ context.Context, opts api.WorkdirOptions) (bool, error)

WorkdirMissing answers workdirMissing over RPC.

func (*Service) Write

func (s *Service) Write(_ context.Context, opts api.WriteOptions) (api.None, error)

Write forwards keyboard input from the window to a session's PTY.

func (*Service) XDGProfileSessions

func (s *Service) XDGProfileSessions(kind, slug string) int

XDGProfileSessions is ProfileSessions for an opencode, Cursor CLI or Kiro CLI profile.

type ServiceCommand added in v0.79.0

type ServiceCommand struct {
	ID          string
	ProjectID   string
	Cwd         string
	Line        string
	Interrupted func()
	Exited      func(code int, tail []byte)
}

ServiceCommand is one run of a service's command on a PTY of its own. Interrupted is told when the user types Ctrl+C at its console, so the exit that follows reads as a stop they asked for. Exited is told once the process is reaped, with its exit status (negative when it left none) and the tail of what it printed, which is all that is left of its console afterwards.

type Store

type Store interface {
	ProviderBin(providerID, projectID string) string
	SkipPermissions(providerID, projectID, cwd string) bool
	Ultracode(providerID string) bool
	PasteUnfold(providerID string) bool
	ProjectPath(projectID string) string
	WorktreePorts() map[string]int
	SetWorktreePort(path string, port int) error
	SetProviderSession(sessionID, providerSessionID string) error
	ConversationHolder(providerSessionID, sessionID string) (string, error)
	ProviderSession(sessionID string) (string, error)
	SessionModel(sessionID string) string
	SessionEffort(sessionID string) string
	SessionProfile(sessionID string) (string, error)
	SessionKind(sessionID string) string
	SetSessionProfile(sessionID, profile string) error
	SessionUltracode(sessionID string) bool
	SessionSubagentDepth(sessionID string) int
	SessionFilesKey(sessionID string) string
	SessionView(sessionID string) string
	InheritUltracode(sessionID, forkedFrom string) error
	InheritSubagent(sessionID, forkedFrom string) error
	SessionSandbox(sessionID string) string
	SetSessionSandbox(sessionID, sandbox string) error
	SetSessionMCPServers(sessionID string, servers []string) error
	SetSessionSandboxLinks(sessionID string, links []string) error
	SandboxDefault(providerID, projectID, cwd string) bool
	SandboxSSHAgent(projectID string) bool
	SandboxGHToken(projectID string) bool
	GHAccountForPath(path string) string
	SetSessionTitle(sessionID, title string) (bool, error)
	SetSessionUnread(_ context.Context, opts api.SessionUnreadOptions) (api.None, error)
	CostReadout() bool
	CostLedger(sessionID, transcriptID string) (int64, string, float64, error)
	SaveCostLedger(sessionID, transcriptID string, offset int64, lastMessage string, cost float64) error
	CountedElsewhere(sessionID, transcriptID, responseID string) (bool, error)
	SaveCostResponses(sessionID, transcriptID string, responseIDs []string) error
	ReplaceConversationCost(sessionID, conversationID string, cost float64) error
	SessionCost(sessionID string) (float64, error)
	SaveForkCostOffset(sessionID, forkedFrom string) error
	AddHandsOn(sessionID string, seconds int64) error
	HandsOn(sessionID string) (int64, error)
}

Store is the persistence the terminal service depends on: the binary to spawn for a provider in a project (empty return spawns the provider's default), whether that spawn drops the provider's permission prompts, turns ultracode on and runs confined, that project's own directory, the dev-server port reserved for each checkout, where to record the provider session id a PTY reports through its session-start hook, where to record a finished turn nobody has read yet, and the running cost accounting behind the footer readout (CostReadout gates it — off, none of the rest is called). The store implements them all.

type TranscriptMatch

type TranscriptMatch = api.TranscriptMatch

type TransportInfo

type TransportInfo struct {
	Port  int    `json:"port"`
	Token string `json:"token"`
}

TransportInfo is where the terminal I/O WebSocket lives, handed to the window at launch (main.go). A zero Port means the transport failed to start.

type TurnState

type TurnState = api.TurnState

Jump to

Keyboard shortcuts

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