terminal

package
v0.90.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0 Imports: 65 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 (
	ModPrompt     = "prompt"
	ModAbort      = "abort"
	ModModel      = "model"
	ModEffort     = "effort"
	ModRunCommand = "command"
	ModAsk        = "ask"
)

The command kinds a Claude Code mod applies for lich (docs/hooks/mod-control.md).

View Source
const (
	ModWithdrawn = "withdrawn" // no poll collected it, so it was taken back and never runs
	ModDelivered = "delivered" // a poll carried it, and no ack came back yet
	ModAcked     = "acked"     // the mod acked it: OK and Error say how it went
	ModEnded     = "ended"     // the session exited or was closed first
)

What RunModCommand learned about a command by the time its wait ended.

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

This section is empty.

Functions

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.

Types

type LastSaid

type LastSaid = api.LastSaid

type ModCommand

type ModCommand struct {
	ID       string `json:"id"`
	Kind     string `json:"kind"`
	Text     string `json:"text,omitempty"`
	Model    string `json:"model,omitempty"`
	Effort   string `json:"effort,omitempty"`
	Name     string `json:"name,omitempty"`
	Args     string `json:"args,omitempty"`
	Question string `json:"question,omitempty"`

	Notification *relay.Notification `json:"notification,omitempty"`
}

ModCommand is one instruction for a session's mod. Model and Effort absent mean "drop the override", which the mod reads as null. Notification makes a prompt one the mod submits as news from outside the session.

type ModOutcome

type ModOutcome struct {
	ID     string
	State  string
	OK     bool
	Error  string
	Answer string
}

ModOutcome is what became of one command: State is one of ModWithdrawn, ModDelivered, ModAcked and ModEnded. Answer is an acked ask's reply.

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) 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) 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) EnqueueModCommand

func (s *Service) EnqueueModCommand(id string, cmd ModCommand) (string, error)

EnqueueModCommand queues cmd for session id's Claude Code mod and returns the id the mod's ack will carry (docs/hooks/mod-control.md). Delivery is at most once and the ack is the only receipt. It fails when the transport is down, when cmd is not a command the contract defines, carries a field of another kind or names a slash command lich refuses, with errModNotRunning when the session has no process, and with errModDetached when no mod is polling from it, which is every running session but a Claude Code one with the lich-plugin mod.

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) ModAnswers

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

ModAnswers is whether running session id's mod answers a subagent errand with its turn's final message: it polls, from a plugin release that does.

func (*Service) ModAttached

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

ModAttached is whether a Claude Code mod polled from running session id within the attach window, which is what SubmitPrompt queues for.

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) Ready

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

Ready answers ready over RPC.

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) 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) 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) RunModCommand

func (s *Service) RunModCommand(ctx context.Context, id string, cmd ModCommand) (ModOutcome, error)

RunModCommand queues cmd like EnqueueModCommand and waits, until ctx ends, for the session's mod to ack it. A wait that ends first is not an error: the outcome says the command was delivered, and still goes through, or withdrawn before any poll collected it, and never runs.

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) 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) 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) SetErrandStatus

func (s *Service) SetErrandStatus(fn func(id string) relay.Status)

SetErrandStatus wires what a mod's status read answers with: the relay's Status. Startup wiring, called once before any session reads.

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) 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) SetWorkerAnswer

func (s *Service) SetWorkerAnswer(fn func(id, text string))

SetWorkerAnswer wires where a worker's reported answer goes: the relay's WorkerAnswered. Startup wiring, called once before any session reports.

func (*Service) SetWorkerUnanswered

func (s *Service) SetWorkerUnanswered(fn func(id, reason string))

SetWorkerUnanswered wires where a worker's turn that ended without an answer goes: the relay's WorkerUnanswered. Startup wiring, like SetWorkerAnswer.

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) 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) SubmitPrompt

func (s *Service) SubmitPrompt(id, text string, note *relay.Notification) (relay.HandedPrompt, error)

SubmitPrompt queues text as a prompt for session id's Claude Code mod, as a notification when note is not nil, with the wait on its ack, which says how far the prompt got once its context ends (relay.PromptReceipt), and whether a poll collected it yet. It answers relay.ErrNoMod for a session no mod can collect it from: the transport is down, the session is not running, or no mod polls from it. The relay is its one caller, and it does none of the relay's ticket accounting.

The wait is a closure because the ack can land before anyone waits on it, and only the waiter queued with the prompt keeps it (modQueue.await).

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) 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
	SubagentCards(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
	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
	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