daemon

package
v0.124.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Overview

Package daemon implements kit's remote-session transport: a daemon mode (`kit daemon`) that hosts kit sessions for paired clients, and a client mode (`kit remote --host <name>`) that attaches a local terminal to that remote session. New clients pair via `kit daemon pair` + `kit remote --pair <code>`.

The transport is iroh, in-process (see iroh.go): endpoint binding, n0 relay and DNS discovery, and the QUIC streams all run inside the kit binary. The wire protocol is v1 — the same protocol the retired Rust kit-tunnel sidecar spoke — so kits from before and after the switch interoperate. See docs in the package files.

Index

Constants

View Source
const (
	// FrameClipboardFlagFinal marks the last chunk of a clipboard transfer.
	FrameClipboardFlagFinal byte = 0x01
	// FrameClipboardFlagClear marks a "clipboard has no image" signal: the
	// client sends it when Ctrl-V found no local image. The daemon clears
	// the session clipboard file so the child's Ctrl-V sees nothing.
	FrameClipboardFlagClear byte = 0x02
)
View Source
const (
	CodeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
	CodeLength   = 8
)

CodeAlphabet excludes 0/O/1/I to keep codes readable and unambiguous when read aloud or copied. 8 characters from a 32-symbol alphabet is ~40 bits of entropy. The code stays valid for the daemon's lifetime and allows multiple sessions; guessing is throttled by the transport's handshake backoff (which also persists across failures), so treat the code like a password for the duration of the daemon run.

View Source
const (
	// RemoteSessionEnv marks a child as running inside a daemon session.
	RemoteSessionEnv = "KIT_REMOTE_SESSION"
	// SessionIDEnv identifies the active local daemon session to its child.
	SessionIDEnv = "KIT_DAEMON_SESSION_ID"

	// RemoteBackgroundEnv holds the CLIENT terminal's background colour as
	// "#rrggbb", or BackgroundUnknown when that terminal was asked and did
	// not answer. The child prefers it over its own OSC query, which would
	// otherwise have to cross the PTY — and, for a remote session, the
	// network — before the first frame is drawn, and which the client,
	// being the side that owns the terminal, can answer without any of it.
	RemoteBackgroundEnv = "KIT_REMOTE_BACKGROUND"
)
View Source
const (
	// ProtocolName identifies this protocol on the wire. It exists so a
	// peer speaking something else entirely is rejected with a clear
	// message rather than by a payload that fails to parse.
	ProtocolName = "kit/daemon"

	// ProtocolVersion is the breaking-change counter.
	//
	// Bump this ONLY when an old peer cannot usefully talk to a new one.
	// Everything that can be expressed as a feature bit must be, because
	// every bump here strands every daemon a user has running.
	//
	// v1 is the format the daemon has spoken since the transport moved
	// in-process: a 7-byte frame header (type, u32 wire session, u16
	// length) and the frame numbers in protocol.go.
	ProtocolVersion uint16 = 1
)
View Source
const (
	RoleClient = "client"
	RoleDaemon = "daemon"
)

Hello roles.

View Source
const BackgroundUnknown = "unknown"

BackgroundUnknown marks a terminal that was asked for its background colour and did not answer.

ProtocolFeatures is everything this build supports.

View Source
const RemoteTerminalFileEnv = "KIT_REMOTE_TERMINAL_FILE"

RemoteTerminalFileEnv names the capability file for a daemon session. The session host replaces this file before sending SIGWINCH to the child. Read it at startup and on each window-size event. A missing file means that live capability updates are not available; keep the current settings.

View Source
const SessionFlag = "--daemon-session"

SessionFlag is the hidden flag every session child is spawned with. It is the marker the crash sweep matches on (see isSessionChild), so it is present whether or not a spec supplied any other argument, and it tells the child it is being hosted rather than run from a shell.

Exported because the flag has to be registered on the kit command as well as passed here, and the two must not be able to drift apart.

View Source
const SessionFlagName = "daemon-session"

SessionFlagName is SessionFlag without the leading dashes, which is how a flag is named when it is registered.

Variables

View Source
var (
	// ErrClipboardTooLarge is returned by the collector when a transfer
	// exceeds clipboardMaxImageSize.
	ErrClipboardTooLarge = errors.New("clipboard image too large")
)
View Source
var ErrNoLocalDaemon = errors.New("daemon: no local daemon is running")

ErrNoLocalDaemon is returned when nothing is listening on the local socket. Callers use it to decide whether to auto-start a daemon.

Functions

func AuthorizeClient

func AuthorizeClient(pubKeyHex string) (string, bool, error)

AuthorizeClient stores a freshly paired client's public key. The returned flag reports whether a NEW allowlist entry was written: an already-known client only gets its LastSeen refreshed, and a caller that must roll a failed pairing back may only remove what it created.

func BackgroundIsDark added in v0.101.2

func BackgroundIsDark(hex string) bool

BackgroundIsDark reports whether a reported background reads as dark.

The test is HSL lightness below one half, which is the test lipgloss applies to a background it queried itself. Sharing the rule means a session started from this environment variable and one started from a live query never disagree about which half of a theme to render. A value that names no colour — BackgroundUnknown among them — reports dark, matching lipgloss's own answer for a terminal that will not say.

func BuildVersion added in v0.111.0

func BuildVersion() string

BuildVersion reports the release version recorded by SetBuildVersion.

func CaptureSessionID added in v0.124.0

func CaptureSessionID() string

CaptureSessionID reads and removes the daemon session ID from the process environment. This prevents child processes from inheriting the parent's ID.

func DecodeResize

func DecodeResize(payload []byte) (cols, rows int, err error)

DecodeResize unpacks a RESIZE payload.

func DialLocal added in v0.101.0

func DialLocal(ctx context.Context) (net.Conn, error)

DialLocal connects to the local daemon's control socket.

The context bounds the dial: a socket that exists but is not being accepted on would otherwise block past the caller's deadline.

func EncodeClipboardChunks

func EncodeClipboardChunks(mediaType string, data []byte) [][]byte

EncodeClipboardChunks splits an image into FrameClipboard payloads. The first chunk carries the media type; each payload's low bit marks the final chunk.

func EncodeHello added in v0.111.0

func EncodeHello(h Hello) ([]byte, error)

EncodeHello renders a HELLO payload.

func EncodeResize

func EncodeResize(cols, rows int) []byte

EncodeResize packs cols/rows into a RESIZE payload.

func EncodeSessionHostInfo added in v0.111.0

func EncodeSessionHostInfo(info SessionHostInfo) ([]byte, error)

EncodeSessionHostInfo renders a supervisor HELLO payload.

func EncodeSessionSpec added in v0.108.0

func EncodeSessionSpec(spec SessionSpec) ([]byte, error)

EncodeSessionSpec renders a SESSION_SPEC payload.

func EncodeTerminalInfo added in v0.101.2

func EncodeTerminalInfo(info TerminalInfo) ([]byte, error)

EncodeTerminalInfo renders a TERMINAL payload.

func Fingerprint

func Fingerprint(raw []byte) string

Fingerprint is the short public identity used in prompts and stores: the first 16 hex chars of SHA-256 over the raw key bytes.

func ForgetHost

func ForgetHost(name string) error

ForgetHost removes a stored host. Returns an error when unknown.

func FormatCode

func FormatCode(code string) string

FormatCode renders a code for display as XXXX-XXXX.

func GenerateCode

func GenerateCode() (string, error)

GenerateCode returns a fresh random pairing code of CodeLength characters.

func HexColor added in v0.101.2

func HexColor(c color.Color) string

HexColor renders a colour as "#rrggbb". color.Color reports 16-bit premultiplied channels, so each is scaled back to 8 bits. A nil colour yields "", which callers read as "the terminal did not say".

func InstallSystemService

func InstallSystemService(ctx context.Context) error

InstallSystemService writes the user unit and enables + starts it. When a daemon is already running interactively, the service's own lock attempt would fail forever, so refuse here instead of creating a restart loop.

func KillHostSession added in v0.124.0

func KillHostSession(ctx context.Context, host string, id uint64) error

KillHostSession stops a session on a paired daemon.

func KillSession added in v0.124.0

func KillSession(ctx context.Context, id uint64) error

KillSession stops a session on the local daemon.

func LoadClientIdentity

func LoadClientIdentity() ([]byte, error)

LoadClientIdentity returns the client's signing seed, creating it on first use.

func LoadDaemonIdentity

func LoadDaemonIdentity() ([]byte, error)

LoadDaemonIdentity returns the daemon's endpoint seed, creating it on first use. The seed doubles as the iroh endpoint secret.

func LocalSocketPath added in v0.101.0

func LocalSocketPath() (string, error)

LocalSocketPath returns the path of the local control socket.

XDG_RUNTIME_DIR is preferred: it is user-private (0700), on tmpfs, and cleared on logout, which is exactly the lifetime a socket wants. The cache dir is the fallback, alongside daemon.lock and daemon.json, so all daemon state stays in one place on systems without a runtime dir.

func NormalizeCode

func NormalizeCode(raw string) (string, error)

NormalizeCode uppercases a code and strips separators/spaces. It rejects anything that is not exactly CodeLength alphabet characters.

func RemoveSystemService

func RemoveSystemService(ctx context.Context) error

RemoveSystemService stops, disables, and deletes the user unit.

func RenameHostSession added in v0.124.0

func RenameHostSession(ctx context.Context, host string, id uint64, name string) error

RenameHostSession changes a session name on a paired daemon.

func RenameSession added in v0.124.0

func RenameSession(ctx context.Context, id uint64, name string) error

RenameSession changes the display name of a session on the local daemon.

func ReportSessionCwd added in v0.101.0

func ReportSessionCwd(dir string)

ReportSessionCwd records the working directory a session settled on, so the daemon can show it in the session list. It is a no-op outside a daemon-hosted session, and a best-effort write: a session list without a directory is a cosmetic loss, never a reason to fail starting up.

func RunClient added in v0.101.0

func RunClient(ctx context.Context, rw io.ReadWriter, opts AttachOptions) (err error)

RunClient drives a daemon connection for the whole client session: pick a session, attach, run, and repeat when the user switches. It returns when the user detaches or the session ends.

It deliberately OUTLIVES the connection. A daemon that is stopped, restarted, upgraded or killed takes its socket with it — but not its sessions, which run in supervisor processes of their own and are adopted by the next daemon (see FeatureReattach and sessionhost.go). A dropped stream is therefore an interruption, not an ending: the client redials, reattaches to the same logical session and repaints. Without this the sessions would survive a daemon restart and the user would still lose every screen they had open, which is most of the point.

The caller owns rw and closes it. Connections opened by a reconnect are owned and closed here.

func RunHost

func RunHost(ctx context.Context, name string, opts AttachOptions) error

RunHost attaches the local terminal to a paired daemon by name: `kit remote --host homelab`. Authentication is by client signing key; no pairing code is involved.

The verified frame stream is handed to RunClient, which owns everything above the transport: session choice, raw mode, the input pumps and the chord table. The local socket path (kit attach) uses the same code.

func RunLocal added in v0.101.0

func RunLocal(ctx context.Context, opts AttachOptions) error

RunLocal attaches the terminal to the local daemon, starting one when none is running.

func RunPair

func RunPair(ctx context.Context, opts PairOptions) error

RunPair performs one-time pairing against a host's pairing window: it proves knowledge of the one-time code, hands the host this machine's signing public key, and stores the host under a friendly name for codeless reconnection with RunHost.

All user-facing messages go to stderr — nothing touches stdout except the eventual remote session.

func RunPairWindow

func RunPairWindow(ctx context.Context, opts PairWindowOptions) error

RunPairWindow opens a one-time pairing window: it derives an ephemeral bootstrap endpoint from a fresh code, shows the code, and — when a client presents it — asks the user to accept or reject on this terminal. On accept the client's public key joins the allowlist and the client learns this daemon's endpoint id; the code is then burned.

The window is independent of the main daemon process: pairing writes the allowlist to disk, and `kit daemon` (running or not) picks it up on the next connection attempt.

func RunSessionHost added in v0.111.0

func RunSessionHost(ctx context.Context, configPath string) error

RunSessionHost is the supervisor's entry point, run as `kit daemon session-host --config <path>`.

It returns when the session's child has exited, which is the only thing that ends a session. Losing the daemon does not: that is the point.

func SaveHost

func SaveHost(name string, endpointID string) error

SaveHost adds (or replaces) a paired host entry under the given name. The endpoint id must be 64 hex chars (an ed25519 public key) so a stored entry can never crash the dial path later.

func SeedFromCode

func SeedFromCode(rawCode string) ([]byte, error)

SeedFromCode derives the 32-byte endpoint seed from a pairing code using HKDF-SHA256 with fixed salt/info. The code is normalized first so both sides agree on every input regardless of how the user typed it.

func Serve

func Serve(ctx context.Context) error

Serve runs the daemon until ctx is cancelled: bind the stable endpoint derived from the daemon identity, then host remote sessions for paired clients. Each client authenticates by signing the handshake with its pairing key; the signature is checked against the allowlist written by `kit daemon pair`. First-time clients pair through `kit daemon pair`, which runs its own short-lived bootstrap endpoint.

func SetBuildVersion added in v0.111.0

func SetBuildVersion(v string)

SetBuildVersion records the release version for the hello and for `kit daemon status`. It is display-only: compatibility is decided by ProtocolVersion, never by this.

func StartLocalDaemon added in v0.101.0

func StartLocalDaemon(ctx context.Context) error

StartLocalDaemon launches a background daemon and waits for its socket.

This is the tmux behaviour: `kit attach` on a machine with no daemon starts one rather than telling the user to. The child is fully detached (its own process group, no inherited terminal) so it outlives the terminal that spawned it — a daemon killed by the hangup of the shell that started it would defeat the point of detachable sessions.

Two clients racing to start a daemon is safe: the loser fails on the single-instance flock and both then connect to the winner's socket.

func TouchClient

func TouchClient(fp string) error

TouchClient updates last_seen after a successful authenticated handshake. Runs under the store lock so a concurrent revoke is never resurrected by a stale read-modify-write.

func TouchHost

func TouchHost(name string) error

TouchHost updates last_used after a successful connection.

func WriteFrame

func WriteFrame(w io.Writer, t FrameType, session uint32, payload []byte) error

WriteFrame writes one frame.

Types

type AttachOptions added in v0.101.0

type AttachOptions struct {
	// Name identifies the daemon in user-facing messages.
	Name string
	// Host is the saved host name this client is connected to, matching
	// the Host the picker reports for this daemon's own sessions. Empty
	// means the local daemon. It is how a cross-host choice is told apart
	// from one on this daemon, so it must be the picker's value, not a
	// display string.
	Host string
	// Reattach is the command that reattaches to this daemon, quoted in
	// the message printed after a detach.
	Reattach string
	// Pick chooses among live sessions. When nil, the client always
	// starts a new session and in-session switching is disabled.
	Pick SessionPicker
	// Target selects a session up front: zero consults Pick, and any
	// other value attaches directly.
	Target uint64
	// ForceNew skips the picker and starts a new session.
	ForceNew bool
	// Hub, when set, handles a cross-host switch request.
	Hub SessionPicker
	// HubEntries supplies sessions from other hosts for the hub picker.
	// The context bounds the queries it makes.
	HubEntries func(ctx context.Context) []SessionEntry
	// Spec describes how a NEW session should be started: the directory
	// the user ran the command in, the arguments they gave it, and the
	// environment it needs. Nil asks for the daemon's default, which is
	// the directory picker in the daemon user's home.
	//
	// Honoured on the local socket only. RunHost clears it: see
	// SessionSpec for why argv must not cross a network boundary.
	Spec *SessionSpec
	// Redial reopens a connection to the SAME daemon after the stream
	// drops, so a daemon that is restarted or upgraded interrupts a
	// session instead of ending it. Nil disables reconnection, and the
	// client then reports a lost connection the way it always did.
	//
	// It must dial the same daemon the client started against: a
	// reconnect reattaches by logical session id, and every daemon numbers
	// its sessions from 1, so a redial that landed somewhere else would
	// silently drop the user into a stranger's session.
	Redial Redialer
}

AttachOptions configures a client attach loop.

type ClientEntry

type ClientEntry struct {
	FP       string    `json:"fp"`     // Fingerprint(client public key)
	PubKey   string    `json:"pubkey"` // 64 hex chars (ed25519 public)
	Label    string    `json:"label"`  // optional note set at pairing time
	AddedAt  time.Time `json:"added_at"`
	LastSeen time.Time `json:"last_seen"`
}

ClientEntry is one paired client, as known on the host.

func ListAuthorized

func ListAuthorized() ([]ClientEntry, error)

ListAuthorized returns all paired clients, sorted by fingerprint.

func LookupClient

func LookupClient(fp string) (ClientEntry, bool, error)

LookupClient verifies a fingerprint is authorized and returns its entry.

func RevokeClient

func RevokeClient(fpOrPrefix string) (ClientEntry, error)

RevokeClient removes an authorized client by fingerprint (or by its unique short prefix). Returns the removed entry.

type ClientKeyPair

type ClientKeyPair struct {
	Seed   []byte
	Priv   ed25519.PrivateKey
	Pub    ed25519.PublicKey
	PubHex string // 64 hex chars
}

ClientKeyPair is the client's signing identity.

func NewClientKeyPair

func NewClientKeyPair(seed []byte) ClientKeyPair

NewClientKeyPair derives the full ed25519 keypair from the stored seed.

type ClipboardCollector

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

ClipboardCollector reassembles a chunked clipboard transfer.

func NewClipboardCollector

func NewClipboardCollector() *ClipboardCollector

NewClipboardCollector returns a collector for one image transfer.

func (*ClipboardCollector) Add

func (c *ClipboardCollector) Add(payload []byte) (done bool, mediaType string, data []byte, err error)

Add consumes one FrameClipboard payload. On the final chunk it returns the complete image; the collector must then be discarded.

type ErrSwitchHost added in v0.101.0

type ErrSwitchHost struct {
	// Host is the saved name of the daemon to connect to.
	Host string
	// Session is the logical session to attach to on that daemon.
	Session uint64
}

ErrSwitchHost reports that the user chose a session on a different daemon. The client speaks to exactly one daemon, so honouring the choice means the caller dials the new host and starts a fresh client; a SessionChoice.Host that this connection cannot reach must never be attached by ID alone, because every daemon numbers its sessions from 1 and the ID would silently resolve to a different session here.

func (*ErrSwitchHost) Error added in v0.101.0

func (e *ErrSwitchHost) Error() string

type Feature added in v0.111.0

type Feature uint64

Feature is one additive capability bit. Peers exchange the set they support in the hello; behaviour behind a bit the other side lacks is simply not used.

const (
	// FeatureTerminalInfo: the peer understands FrameTerminal, so a
	// session's child can be told what terminal it renders in.
	FeatureTerminalInfo Feature = 1 << 0
	// FeatureSessionSpec: the peer understands FrameSessionSpec, so a
	// local session starts in the caller's directory with the caller's
	// arguments instead of behind the directory picker.
	FeatureSessionSpec Feature = 1 << 1
	// FeatureTermModes: the daemon replays a session's terminal modes to
	// a client that attaches mid-session.
	FeatureTermModes Feature = 1 << 2
	// FeatureClipboard: the peer understands FrameClipboard image
	// transfer.
	FeatureClipboard Feature = 1 << 3
	// FeatureSessionRename: the peer understands FrameSessionRename.
	FeatureSessionRename Feature = 1 << 4
	// FeatureSessionRedraw: the peer understands FrameSessionRedraw.
	FeatureSessionRedraw Feature = 1 << 5
	// FeatureReattach: this daemon hosts its sessions in separate
	// supervisor processes, so they survive it being stopped, restarted
	// or killed, and it adopts them again when it comes back.
	//
	// A client uses the bit to decide what to say when a connection
	// drops: with it, "the daemon went away, your session is still
	// running, reconnecting"; without it, the session died with the
	// daemon and there is nothing to reconnect to.
	FeatureReattach Feature = 1 << 6
	// FeatureScrollback: an attaching client is sent the session's recent
	// output, so the screen is restored without waiting for the child to
	// repaint.
	FeatureScrollback Feature = 1 << 7
	// FeatureSessionSpecParts: the daemon joins FrameSessionSpecPart
	// frames, so a SessionSpec larger than one frame (a large
	// environment) arrives complete instead of being trimmed.
	FeatureSessionSpecParts Feature = 1 << 8
	// FeatureSessionControl: the peer supports acknowledged rename and kill requests.
	FeatureSessionControl Feature = 1 << 9
)

func (Feature) Has added in v0.111.0

func (f Feature) Has(want Feature) bool

Has reports whether every bit in want is present.

func (Feature) String added in v0.111.0

func (f Feature) String() string

String renders a feature set as a comma-separated list.

type Frame

type Frame struct {
	Type    FrameType
	Session uint32
	Payload []byte
}

Frame is one relayed message. Session 0 is used by clients (the daemon stamps the assigned wire id on arrival) and in tests.

func ReadFrame

func ReadFrame(r io.Reader) (Frame, error)

ReadFrame reads one frame. Returns io.EOF when the reader ends cleanly on a frame boundary (peer closed).

type FrameType

type FrameType byte

Frame types (protocol v1, shared by every kit build — including the retired Rust kit-tunnel sidecar). Data/resize/bye travel end-to-end, multiplexed by session id; ping/pong are reserved for a future keepalive; the 0x1x handshake frames are consumed during the transport handshake and never reach the session frame loop (see iroh.go).

const (
	FrameData   FrameType = 0x01
	FrameResize FrameType = 0x02
	FrameBye    FrameType = 0x03
	FramePing   FrameType = 0x04
	FramePong   FrameType = 0x05

	// Client -> daemon clipboard image transfer (chunked; see
	// internal/daemon/clipboard.go for the payload layout). Travels
	// end-to-end like DATA/RESIZE; consumed by the daemon, never written
	// to the session PTY.
	FrameClipboard FrameType = 0x06

	// Session lifecycle (travels end-to-end like CLIPBOARD). Sessions are
	// LOGICAL: they outlive client connections, so a client can detach
	// (Ctrl+X d) and later reattach, and several clients can attach to
	// the same session (shared tmux-style view). Wire session ids are per
	// connection; the daemon maps them to logical sessions.
	FrameSessionDetach    FrameType = 0x07 // client -> daemon: unbind me, keep the session
	FrameSessionList      FrameType = 0x08 // client -> daemon: list live sessions (payload empty)
	FrameSessionListReply FrameType = 0x09 // daemon -> client: JSON [{id,clients,started,cwd,name}]
	FrameSessionAttach    FrameType = 0x0a // client -> daemon: {logical id u64 BE}
	FrameSessionAttachAck FrameType = 0x0b // daemon -> client: {logical id u64 BE, ok 0|1}
	// FrameSessionRedraw asks the daemon to make the session's child
	// repaint. A client that has just attached inherits a screen the child
	// already drew, so without this the terminal stays blank until the
	// next keystroke. The daemon nudges the PTY size, which is what makes
	// a full-screen TUI redraw; doing it daemon-side keeps the two size
	// changes off the network, where the round trip made the old
	// client-side version of this trick unreliable.
	//
	// The daemon answers it with the session's terminal modes (mouse,
	// bracketed paste, focus, cursor, keyboard protocol) as ordinary data
	// first: a client that attaches to a running session never saw the
	// child set them, because a TUI sends each mode sequence once. See
	// termModes.
	FrameSessionRedraw FrameType = 0x0c // client -> daemon: repaint (payload empty)
	// FrameSessionRename sets a session's display name so a list of many
	// sessions stays readable.
	FrameSessionRename        FrameType = 0x0d // client -> daemon: {id u64 BE, name UTF-8}
	FrameSessionKill          FrameType = 0x1a // client -> daemon: {id u64 BE}
	FrameSessionControlResult FrameType = 0x1b // daemon -> client: JSON {error,omitempty}
	// FrameTerminal describes the CLIENT's terminal to the daemon (JSON,
	// see TerminalInfo). A daemon owns a PTY, not a terminal, and a PTY
	// reports no colour depth and answers no background-colour query, so
	// without this a session's child describes the daemon's own
	// environment — under a service manager, no terminal at all. Sent
	// before SESSION_ATTACH so a new session's child is spawned already
	// describing the terminal it will be seen in.
	FrameTerminal FrameType = 0x0e // client -> daemon: JSON TerminalInfo
	// FrameSessionSpec describes the command line a NEW session should be
	// started as: a working directory, the arguments to pass, and the
	// environment variables to layer on the daemon's own (JSON, see
	// SessionSpec). Without it a new session always starts in the daemon
	// user's home directory behind the directory picker, which is right
	// for 'kit attach' but wrong for a plain 'kit' in a project directory.
	// Sent before SESSION_ATTACH, like TERMINAL; a daemon too old to know
	// the frame drops it and starts the session the old way.
	FrameSessionSpec FrameType = 0x0f // client -> daemon: JSON SessionSpec
	// FrameSessionSpecPart carries one piece of a SessionSpec too large
	// for a single frame. A full environment (a nix dev shell, a large
	// direnv) can pass the 64 KiB frame limit, and dropping it would start
	// the session with the daemon's environment instead of the caller's.
	//
	// The first payload byte is specPartMore when more parts follow and
	// specPartLast on the last one; the rest is the next slice of the JSON
	// SessionSpec. The daemon joins the parts and handles the result as a
	// FrameSessionSpec. Sent only to a daemon that advertises
	// FeatureSessionSpecParts.
	FrameSessionSpecPart FrameType = 0x19 // client -> daemon: {more u8, JSON slice}

	// FrameHello announces which protocol a peer speaks and what it can
	// do (JSON, see Hello). Both ends send it first and neither waits for
	// the other's: a peer too old to know the frame drops it, and silence
	// is read as "protocol v1, no optional features" rather than as a
	// failure. See version.go for why compatibility is one rarely-changing
	// number plus an additive feature bitmap.
	//
	// 0x15 sits in the gap left by the retired SESSION_OPEN/CLOSED pair so
	// the session frames stay contiguous.
	FrameHello FrameType = 0x15 // both ways: JSON Hello

	// Historical frame types (retired with the Rust kit-tunnel sidecar,
	// which owned the transport in a subprocess). SESSION_OPEN/CLOSED
	// introduced and retired wire connections on the sidecar's stdio; the
	// 0x30/0x4x frames were the daemon<->sidecar consultation channel that
	// kept authentication and pairing policy in Go. The transport now runs
	// in-process (iroh.go), which makes them unnecessary — the values stay
	// reserved so protocol v1 keeps one authoritative number space.
	FrameSessionOpen   FrameType = 0x16
	FrameSessionClosed FrameType = 0x17
	FrameAuthRequest   FrameType = 0x30
	FrameAuthPayload   FrameType = 0x31
	FrameAuthDecision  FrameType = 0x32
	// FramePairRequest and FramePairCancel are still used in-process: the
	// pairing window surfaces attempts to the operator loop as these
	// frames (see iroh_pair.go and pair.go).
	FramePairRequest  FrameType = 0x40
	FramePairDecision FrameType = 0x41
	FramePairCancel   FrameType = 0x42
)

type Hello added in v0.111.0

type Hello struct {
	// Protocol is ProtocolName. A different value is a different program.
	Protocol string `json:"protocol"`
	// Version is ProtocolVersion: the compatibility decision.
	Version uint16 `json:"version"`
	// Features is the sender's ProtocolFeatures bitmap.
	Features Feature `json:"features"`
	// Build is the sender's release version, for display only.
	Build string `json:"build,omitempty"`
	// Role is "client" or "daemon", so a log line says which end it came
	// from without the reader having to infer it.
	Role string `json:"role,omitempty"`
	// PID is the sender's process id, for display only.
	PID int `json:"pid,omitempty"`
}

Hello is the first frame each side sends on a connection: who I am, which protocol I speak, and what I can do.

JSON rather than a packed struct on purpose. The whole point of this frame is that a peer from another release can read it, which means an unknown field must be ignorable and a missing field must have a sensible zero — exactly what a JSON object gives and a fixed byte layout does not.

func DecodeHello added in v0.111.0

func DecodeHello(payload []byte) (Hello, error)

DecodeHello parses a HELLO payload.

func (Hello) Compatible added in v0.111.0

func (h Hello) Compatible() error

Compatible reports whether a peer's hello can be served, and why not when it cannot.

Only two things are fatal: a different protocol entirely, and a different version. Features never are — that is the whole reason they are separate.

type HostEntry

type HostEntry struct {
	Name       string    `json:"name"`
	EndpointID string    `json:"endpoint_id"` // 64 hex chars (ed25519 public key)
	HostFP     string    `json:"host_fp"`     // Fingerprint(EndpointID)
	AddedAt    time.Time `json:"added_at"`
	LastUsed   time.Time `json:"last_used"`
}

HostEntry is one paired daemon, as known on the client.

func GetHost

func GetHost(name string) (HostEntry, error)

GetHost returns the stored entry for name.

func ListHosts

func ListHosts() ([]HostEntry, error)

ListHosts returns all paired hosts, sorted by name.

type IdentityPaths

type IdentityPaths struct {
	DaemonSeed string // daemon endpoint seed (~/.config/kit/daemon/identity.key)
	ClientSeed string // client signing seed (~/.config/kit/remote/identity.key)
}

IdentityPaths resolves the key file locations under ~/.config/kit.

type PairOptions

type PairOptions struct {
	// Name pre-selects the saved host name (skips the interactive prompt).
	Name string
	// Code is the one-time pairing code shown by 'kit daemon pair'.
	Code string
}

PairOptions controls `kit remote --pair`. Code is required; all other fields are optional.

type PairWindowOptions

type PairWindowOptions struct {
	// Code forces a specific pairing code instead of a random one.
	// Intended for tests.
	Code string
	// Prompt overrides the interactive accept/reject decision (tests).
	// When nil, the decision is made on the terminal; a non-TTY stdin
	// always denies. Implementations should return false when ctx ends.
	Prompt func(ctx context.Context, fp string) bool
	// Window bounds the pairing window. Zero means the default (10 min).
	Window time.Duration
}

PairWindowOptions controls `kit daemon pair`. Zero values are valid.

type Redialer added in v0.111.0

type Redialer func(ctx context.Context) (io.ReadWriter, func(), error)

Redialer opens a fresh connection to a daemon. It returns the frame stream and a function that releases it; the caller owns both.

type SessionChoice added in v0.101.0

type SessionChoice struct {
	// ID is the logical session to attach to. Zero means "start a new
	// session" unless Cancel is set.
	ID uint64
	// Host names the daemon the session belongs to, for the multi-host
	// picker. Empty means the daemon currently connected.
	Host string
	// Cancel reports that the user dismissed the picker.
	Cancel bool
}

SessionChoice is what a picker returns.

type SessionEntry added in v0.101.0

type SessionEntry struct {
	ID      uint64
	Clients int
	Started time.Time
	Cwd     string
	Name    string
	// Host is the saved host name a session belongs to. Empty for the
	// local daemon; set by the hub when several daemons are listed at once.
	Host string
}

SessionEntry describes one live session on a daemon, as reported by the session list. It is the daemon's own type so the picker can be supplied by the caller: the UI layer converts to its own view model, which keeps internal/daemon free of a dependency on internal/ui.

func ListHostSessions added in v0.101.0

func ListHostSessions(ctx context.Context, name string, timeout time.Duration) ([]SessionEntry, error)

ListHostSessions queries one paired host's live sessions without attaching, for the multi-host picker. The whole exchange is bounded by timeout: an unreachable host must not stall a picker that has other hosts to show.

ctx cancels the query early. The picker queries every paired host at once, so a caller that gives up must be able to take the dials down without waiting out the timeout.

func ListLocalSessions added in v0.101.0

func ListLocalSessions(ctx context.Context) ([]SessionEntry, error)

ListLocalSessions reports the local daemon's live sessions without attaching. Returns ErrNoLocalDaemon when nothing is running, so a caller can distinguish "no daemon" from "a daemon with no sessions".

type SessionHostConfig added in v0.111.0

type SessionHostConfig struct {
	// ID is the logical session id, matching the socket name.
	ID uint64 `json:"id"`
	// Socket is the path to listen on.
	Socket string `json:"socket"`
	// Spec describes the command line to run, or nil for the daemon's
	// default (the directory picker in the user's home).
	Spec *SessionSpec `json:"spec,omitempty"`
	// Terminal describes the terminal of the client that asked for this
	// session, so the child renders for it rather than for the daemon.
	Terminal TerminalInfo `json:"terminal"`
	// Env holds the per-session variables the daemon owns: the clipboard
	// file, the cwd report file, and the ownership marker.
	Env map[string]string `json:"env,omitempty"`
	// Name is the session's display name, empty until it is renamed.
	Name string `json:"name,omitempty"`
	// Owner is the daemon runtime directory that started this session. A
	// supervisor records it so a sweep can prove the process is its own
	// before signalling it.
	Owner string `json:"owner,omitempty"`
}

SessionHostConfig is everything a supervisor needs to start and serve one session. The daemon writes it to a private file and passes the path; the supervisor reads it once and removes it.

A file rather than arguments or environment: it carries the caller's whole environment, which is far larger than an argument list may safely be, and it keeps that environment out of the process table where any other process on the machine could read it.

type SessionHostInfo added in v0.111.0

type SessionHostInfo struct {
	// Protocol, Version and Features describe the supervisor exactly as a
	// daemon's own hello describes it. A supervisor is a long-lived
	// process too, and a daemon upgraded underneath it meets the same
	// skew a client meets, so it is settled the same way.
	Protocol string  `json:"protocol"`
	Version  uint16  `json:"version"`
	Features Feature `json:"features"`
	Build    string  `json:"build,omitempty"`

	// ID is the logical session id.
	ID uint64 `json:"id"`
	// PID is the supervisor's own process id.
	PID int `json:"pid"`
	// ChildPID is the kit process inside the session.
	ChildPID int `json:"child_pid"`
	// Started is when the session began, not when the supervisor was
	// last dialled: a session's age must not reset because a daemon did.
	Started time.Time `json:"started"`
	// Name is the display name, empty when it has none.
	Name string `json:"name,omitempty"`
	// Cwd is the session's working directory, empty while the directory
	// picker is still on screen.
	Cwd string `json:"cwd,omitempty"`
	// Owner is the runtime directory of the daemon that started this
	// session; a daemon refuses to adopt a session owned by another.
	Owner string `json:"owner,omitempty"`
}

SessionHostInfo is the supervisor's HELLO: what a daemon needs to put a session it has never seen back into its table.

func DecodeSessionHostInfo added in v0.111.0

func DecodeSessionHostInfo(payload []byte) (SessionHostInfo, error)

DecodeSessionHostInfo parses a supervisor HELLO payload.

func (SessionHostInfo) Compatible added in v0.111.0

func (i SessionHostInfo) Compatible() error

Compatible reports whether a daemon can drive this supervisor.

Same rule as everywhere else: the protocol version decides, features never do. A supervisor from another protocol version is left strictly alone — not adopted, and above all not killed, because the session inside it is somebody's work and an unreadable supervisor is no reason to destroy it.

type SessionPicker added in v0.101.0

type SessionPicker func(ctx context.Context, entries []SessionEntry, input *os.File) (SessionChoice, error)

SessionPicker presents live sessions and returns the user's choice. It runs with the terminal in cooked mode and owns the screen while it runs.

input is the terminal input the picker must read from. The client keeps a single reader on os.Stdin for its whole life, so a picker that opened its own would race it for keystrokes.

ctx cancels the picker. It is the one blocking call in an attached client that the user cannot always end from the keyboard, so it has to honour the same cancellation as the session loop around it.

type SessionSpec added in v0.108.0

type SessionSpec struct {
	// Cwd is the directory the session starts in. An empty or missing
	// directory falls back to the daemon user's home.
	Cwd string `json:"cwd,omitempty"`
	// Args are the arguments to pass to the session's kit process,
	// without the program name.
	Args []string `json:"args,omitempty"`
	// Env holds the client's environment variables. Keys the daemon owns
	// are ignored; see reservedSpecEnv.
	Env map[string]string `json:"env,omitempty"`
	// FullEnv marks Env as the client's COMPLETE environment. The session
	// then gets exactly that environment, plus only the variables the
	// daemon owns, instead of Env layered on the daemon's environment.
	// This is what makes a hosted session see the same variables as a kit
	// run in the shell, including a variable the shell has unset.
	//
	// A daemon too old to know the field layers Env on its own
	// environment, which is the previous behaviour.
	FullEnv bool `json:"full_env,omitempty"`
	// Pick asks for the working-directory picker, rooted at Cwd, instead
	// of starting straight away.
	//
	// This is what `kit attach` asks for: the user said which MACHINE they
	// wanted a session on, not which directory, so they are still offered
	// the choice — but offered it where they are standing rather than in
	// their home directory. A routed `kit` leaves it false, because there
	// the directory is the whole point.
	Pick bool `json:"pick,omitempty"`
}

SessionSpec describes how to start a NEW session, so a session hosted by the daemon begins where the user ran the command rather than in the daemon's home directory.

The daemon inherits nothing from the client: it is a separate process, usually started by a service manager, with its own working directory and its own environment. A session spawned from it therefore has to be told all three parts explicitly.

A spec is honoured only on the LOCAL socket. A working directory and an argument list from another machine name nothing that exists on this one, and accepting argv over the network would turn a paired client into arbitrary execution. The local socket is already restricted to the daemon's own user, so a spec there grants no more than running kit directly would.

func DecodeSessionSpec added in v0.108.0

func DecodeSessionSpec(payload []byte) (SessionSpec, error)

DecodeSessionSpec parses a SESSION_SPEC payload.

func SessionSpecForCommand added in v0.108.0

func SessionSpecForCommand(cwd string, args []string) SessionSpec

SessionSpecForCommand describes the invocation the caller wants a daemon-hosted session to reproduce: the directory it was run in, the arguments it was given, and the part of its environment a session legitimately needs.

args is the argument list WITHOUT the program name, exactly as os.Args[1:] reports it.

func SessionSpecForPicker added in v0.108.0

func SessionSpecForPicker(cwd string) SessionSpec

SessionSpecForPicker describes a client that wants to choose a directory rather than name one: `kit attach`, which asks for a session on this machine without saying where.

The directory still travels, because it decides where the picker opens. Rooting it at the client's own directory rather than at the daemon user's home is the difference between one keystroke and navigating back to the project the user was already in.

type Status

type Status struct {
	// Running is true when a live process holds the daemon lock.
	Running bool
	// State is the daemon's last persisted snapshot, nil when none exists.
	// For a stopped daemon this is stale data from a previous run.
	State *daemonState
}

Status describes a kit daemon on this machine (per user).

func ReadStatus

func ReadStatus() Status

ReadStatus reports whether a daemon currently holds the lock. Probing is a non-blocking exclusive flock: acquiring it means no daemon is alive.

type TerminalInfo added in v0.101.2

type TerminalInfo struct {
	Term      string `json:"term,omitempty"`
	ColorTerm string `json:"colorterm,omitempty"`
	// ColorProfile is the detected color depth, absent for older clients.
	// Values match colorprofile.Profile (1 through 5).
	ColorProfile *int `json:"color_profile,omitempty"`
	// Background is the terminal background as "#rrggbb", or
	// BackgroundUnknown when the terminal was asked and did not answer.
	// The two are distinct on purpose: "asked, no answer" tells the child
	// not to spend its own startup asking again, where an empty value (a
	// client too old to probe at all) leaves it free to try.
	Background string `json:"background,omitempty"`
	// Multiplexer names the terminal multiplexer the client runs inside
	// ("tmux", "screen", "zellij"), or is empty for a bare terminal. A
	// multiplexer's pane variables describe a process's own pane and so
	// never cross the wire; without this the child probes a terminal that
	// answers from behind one and then draws graphics the multiplexer
	// discards. See termgfx.RemoteMultiplexerEnv.
	Multiplexer string `json:"multiplexer,omitempty"`
}

TerminalInfo describes the client terminal a session is rendered in. The daemon cannot observe any of it: it owns the PTY, and a PTY answers no capability queries of its own.

Term and ColorTerm are forwarded into the child's environment the way ssh forwards TERM, so colour-depth detection sees the user's terminal. Background is the terminal's own background colour, which decides whether a theme renders its light or its dark palette; the client resolves it locally because the OSC query that answers it must otherwise cross a PTY and a network before the first frame is drawn.

func DecodeTerminalInfo added in v0.101.2

func DecodeTerminalInfo(payload []byte) (TerminalInfo, error)

DecodeTerminalInfo parses a TERMINAL payload.

func ReadTerminalCapabilities added in v0.122.0

func ReadTerminalCapabilities(path string) (TerminalInfo, error)

ReadTerminalCapabilities reads the latest attached terminal's capabilities. ColorProfile is optional for compatibility with older clients. Its numeric values are 1 (no terminal), 2 (no color), 3 (16 colors), 4 (256 colors), and 5 (true color). An empty background means it was not reported; BackgroundUnknown means the client queried it but received no answer.

Jump to

Keyboard shortcuts

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