convo

package
v0.16.521 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 51 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 convo owns the conversations of a runtime: one actor per conversation writes its record, agent state, queue, messages, gates, background tasks and seenAt, and every change it makes goes out as a wire event.

This file is the seam between the actors and the protocol: internal/wire serves the socket, the commands and the pages on a Service, and the actors publish through a Publisher. Either side can be faked against it.

Index

Constants

View Source
const (
	// FeedKept is how long the feed of a chat nobody reads keeps what it read (releaseQuietFeed).
	FeedKept = 5 * time.Minute

	// LookEvery is how often an actor looks at its pane and reads its transcript when nothing told it to.
	LookEvery = time.Second
	// LookResting is how often an agent at rest at its prompt is looked at and its clock turns when nothing told it to:
	// its hooks say when it starts to work or goes, and a message or a hook wakes its actor at once. A runtime holds a
	// hundred and more such chats, and each look is a few tmux calls.
	LookResting = 15 * time.Second
	// LookGone is how often a chat whose agent is gone, stopped or failed to start is looked at: only to see whether its
	// session came back or went.
	LookGone = 10 * time.Second
	// LookAbsent is how often a stopped chat, or one whose launch failed, is looked at once a look found no tmux session
	// of it: a runtime holds hundreds of them, and a look every ten seconds each was a goroutine, a listing and a read
	// of the transcript's size for a session that is not there.
	LookAbsent = 5 * time.Minute
	// LookStarting is how often a starting agent's pane is looked at: the moment it can take the first message is
	// noticed by its screen (BootSettle) when the SessionStart hook is late or lost, so a look a second apart made the
	// first message wait up to a second more for nothing. A look is two tmux calls (pane info, capture) off the actor and
	// never two at once (observe), and only the few conversations that are starting look this often.
	LookStarting = 250 * time.Millisecond
	// LookLate is how often a chat whose turn its stop hook ended before the transcript had the agent's last lines is
	// read: the answer is written a moment after the hook, and the pace of a chat at rest (LookResting) kept it off the
	// page for up to 15 s. LateWatch is how long after the hook it is read that often.
	LookLate  = 250 * time.Millisecond
	LateWatch = 30 * time.Second
	// BootSettle is how long a freshly started agent's screen must stand unchanged, its input box drawn, before it
	// counts as ready for the first message. Kept at 1.5 s on purpose: Claude 2.1.317 on a loaded machine was
	// seen not showing keys typed up to two seconds after its box was drawn, and a lost first Enter costs more (a retry
	// backing off from 1.5 s) than the settle does. What made the launch slow was the look a second apart, not this.
	BootSettle = 1500 * time.Millisecond
	// QuietAfter is how long a working or unknown agent must look quiet — not busy, its prompt box up, no menu, the
	// transcript not growing — before the actor takes it as done.
	QuietAfter = 15 * time.Second
	// QuietUnmarked is how long a Claude turn the transcript keeps open must stay quiet to count as done when the screen
	// does not say it ended: a reply the model is slow to start writes nothing (96 s seen) and its spinner may be
	// unread, so silence alone is a turn at work. Past it silence counts again: a lost Stop must not keep a turn open
	// forever.
	QuietUnmarked = 10 * time.Minute
	// LaunchNoAgent is how long a starting agent's pane may show a bare shell before the launch counts as failed: the
	// launch line is typed into a shell, so a shell is expected for a moment, but one that stays means the agent
	// exited or never ran (a broken CLI). Without it the launch waited out its whole deadline, and a «Continue
	// sending» pressed meanwhile found the conversation still starting and launched nothing.
	LaunchNoAgent = 15 * time.Second
	// TmuxLostFor is how long a chat taken for gone by a session not found waits for its pane to come back. A loaded
	// machine's tmux may fail to answer for a while; a session still missing after this is gone for good (the runtime
	// restarted, tmux was killed), and a chat with an agent session to resume becomes a stopped one its queue resumes.
	// Without it the chat stayed gone, its messages queued under «агента нет» with nothing to start the agent.
	TmuxLostFor = 2 * time.Minute
	// CompactHold is how long a compaction (PreCompact, and neither PostCompact nor the transcript's compaction line
	// yet) keeps a working agent from counting as quiet. Claude writes nothing to the transcript while it compacts
	// (45–95 s seen), and its screen may not read busy. Past the hold silence counts again: a lost PostCompact must not
	// keep a turn open forever.
	CompactHold = 10 * time.Minute
	// StateCoalesce: conversation_state and conversation_upsert of one conversation go at most this often.
	StateCoalesce = 100 * time.Millisecond
	// SaveEvery: a conversation is written at most five times a second.
	SaveEvery = 200 * time.Millisecond
	// GateKept is how long a gate stays in the snapshot after it closed or was answered.
	GateKept = 10 * time.Minute
	// DeletedKept is how long a deleted conversation can be restored.
	DeletedKept = 7 * 24 * time.Hour
)
View Source
const (
	LimitContinueText   = "Продолжай с того места, где остановился"
	RestartContinueText = "Продолжай — работа была прервана перезапуском"
	// RestartBackgroundText goes to an agent whose prompt was free but that waited for background work when it was cut:
	// that work died with it, and it must know to start again what it still needs.
	RestartBackgroundText = "" /* 321-byte string literal not displayed */
)

The words the runtime writes to an agent to go on by itself: after its usage limit reset, after a restart of the runtime cut its turn short.

View Source
const (
	// PeerClientPrefix starts the client id of every message from another agent.
	PeerClientPrefix = "peer-"
	// PeerDevice is the device such a message is sent from.
	PeerDevice = "peer"
)

A message from another agent (internal/peers) enters a conversation here and only here: the same outbox as the person's messages — so it waits, is typed and is confirmed the same way — under a client id of its own, from a device of its own. Nothing in the outbox or the typist knows the difference; the feed tells it by the envelope in the text.

View Source
const (
	// RoutineClientPrefix starts the client id of every routine's run put into a chat.
	RoutineClientPrefix = "routine-"
	// RoutineDevice is the device such a message is sent from.
	RoutineDevice = "routine"
)

A run of a routine that continues a chat (docs/hub/routines.md) enters the chat here: the hub's prompt goes into the chat's outbox like a message of the person — it waits for the turn that runs to end, it wakes a chat whose terminal was stopped or did not outlive a restart — under a client id of its own, from a device of its own. The run's id makes the client id, so a start the hub asks for twice is queued once.

View Source
const (
	// OpsKept is how long the answer to an opId is kept, OpsMax how many at most.
	OpsKept = 24 * time.Hour
	OpsMax  = 5000
)
View Source
const ChatRefBudget = 18000

ChatRefBudget is how many characters of another chat a message carries under its words (about 6 000 tokens).

View Source
const DialogHold = 5 * time.Second

DialogHold is how long a menu nobody announced stands on the screen before the chat asks the person about it: the typist's own dialogs and the menus that go by themselves are gone by then.

View Source
const LimitRetryMin = 5 * time.Minute

LimitRetryMin is how soon at the earliest a chat held on its limit goes on by itself: a reset the agent names that is already past (a stale one) must not send it round a loop of refusals.

View Source
const LimitScreenFresh = 5 * time.Minute

LimitScreenFresh is how recent the end of the last turn must be for Codex's notice on the screen to hold the chat: an old notice still on the screen after a restart is history.

View Source
const (
	// ReapEvery is how often the sweep looks at the chats.
	ReapEvery = 5 * time.Minute
)
View Source
const RestartResumeAfter = 45 * time.Second

RestartResumeAfter is how long a chat a restart cut short waits for the startup's resume to bring its terminal back before it resumes the agent itself.

Variables

View Source
var (
	ActorRestartAfter = 5 * time.Second
	ActorRestartMax   = 5 * time.Minute
)

ActorRestartAfter is how long an actor that panicked waits before it runs again; the wait doubles with every panic in a row, up to ActorRestartMax.

View Source
var (
	// ErrNotFound is a conversation, turn or entry the runtime does not have.
	ErrNotFound = errors.New("convo: not found")
	// ErrUnknownCursor is an afterEntryId that is not in the transcript.
	ErrUnknownCursor = errors.New("convo: unknown cursor")
	// ErrBusy is a conversation whose mailbox stayed full: its actor is stuck, and the message was not taken.
	ErrBusy = errors.New("convo: the conversation's mailbox is full")
)
View Source
var (
	WriteRetry    = time.Second
	WriteRetryMax = time.Minute
	FlushWait     = 10 * time.Second
)

A write that failed is tried again after WriteRetry, twice as long after every failure in a row, up to WriteRetryMax. FlushWait is how long Close waits for the writes it holds.

View Source
var ErrInputUncertain = errors.New("the agent's channel did not say whether it took the message")

ErrInputUncertain: the channel broke after the message was written, and the agent does not show it.

View Source
var ErrMoveNoHistory = errors.New("the conversation has no history to move")

ErrMoveNoHistory: the conversation has no complete record to carry.

View Source
var ErrNoTranscript = errors.New("the conversation has no transcript yet")

ErrNoTranscript: the conversation's agent has written no transcript yet, so there is no context to carry.

View Source
var ErrResumeBlocked = errors.New("the tab's terminal is busy")

ErrResumeBlocked is a resume refused because something else holds the tab's terminal.

View Source
var MailWait = 5 * time.Second

MailWait is how long a message that needs no answer waits for room in a full mailbox before it is dropped.

View Source
var NotSavedAfter = 3

NotSavedAfter is how many writes of a conversation must fail in a row before its record says it is not saved.

View Source
var UnloadAfter = 6 * time.Hour

UnloadAfter is how long a conversation at rest goes unasked for before its actor is let go.

Functions

func IsPeerClientID

func IsPeerClientID(id string) bool

IsPeerClientID says whether a message of the outbox came from another agent.

func IsRoutineClientID

func IsRoutineClientID(id string) bool

IsRoutineClientID says whether a message of the outbox is a routine's run.

func LegacyQueue

func LegacyQueue(file string) (map[string][]outbox.LegacyItem, error)

LegacyQueue reads Legacy's prompt-queue.json: tab id → its messages, oldest first. An entry that does not have its fields' types is skipped, as Legacy's own loader does; a missing file is no queue.

func ResolveProfileModel

func ResolveProfileModel(profiles Profiles, p wire.Provider, profile string, model wire.Model, useDefault bool) (*wire.Model, wire.RefuseCode)

ResolveProfileModel checks a requested profile against the same account, CLI, model and effort catalog used by chats.

Types

type AgentSession

type AgentSession struct {
	Title          string
	Cwd            string
	TranscriptPath string
}

AgentSession is a session an agent CLI kept on the machine.

type Background

type Background interface {
	// Tasks are the tasks running now. pane is the agent's screen as the last look saw it ("" when there was none):
	// the footer of an agent that counts its shells is the authority on how many run.
	Tasks(c wire.Conversation, pane string) []wire.BackgroundTask
	// Stop ends a task the agent can no longer be asked about, and returns once it is over; an error when it cannot be
	// found or does not end.
	Stop(c wire.Conversation, taskID string) error
}

Background reads and ends the work an agent runs beside its turn: shells, monitors, subagents.

type ChannelForgetter

type ChannelForgetter interface {
	Forget(ch wire.Channel) bool
}

ChannelForgetter is a Publisher that keeps something for every channel: Forget drops a conversation's channel no page holds, and says whether it is gone.

type Clock

type Clock interface {
	typist.Clock
	// After fires once at d from now.
	After(d time.Duration) <-chan time.Time
}

Clock is the actors' time: now, and a timer the runner waits on. Tests move it by hand.

type Closer

type Closer interface {
	// Close kills the tmux session of the conversation and removes its tab from the layout; it returns once both are done.
	Close(c wire.Conversation) error
}

Closer ends a conversation's pane and its tab: what a deleted conversation leaves behind.

type Configurer

type Configurer interface {
	Configure(ctx context.Context, conv wire.Conversation, model string, effort *wire.Effort, permission wire.PermissionMode) error
}

Configurer is an Input that changes the model, the effort and the permission mode of the running agent: "" and nil leave one as it is.

type CronKeeper

type CronKeeper interface {
	// Crons is how many of the agent's cron jobs made since since (epoch ms; 0: any) are still pending. A job made
	// before the agent's process last started died with the process before it.
	Crons(c wire.Conversation, since wire.Ms) int
}

CronKeeper is a Background that also knows the agent's pending cron jobs (Claude Code's CronCreate, /loop with an interval). They live only in the agent's session: a chat that holds one is not stopped for standing idle.

type Deps

type Deps struct {
	// PersonOf is the address of the person a command's context carries (their page session), "" for the runtime's own
	// person; a new conversation keeps it (wire.Conversation.Person). nil: every chat is the runtime's person's.
	PersonOf func(context.Context) string

	MachineID string
	Publisher Publisher
	// ProjectsChanged is told the machine's whole project list after a project was made or changed; it must
	// not block. nil: nobody listens.
	ProjectsChanged func([]wire.Project)
	Machine         Machine
	Launcher        Launcher
	// Input is the structured channel some conversations take their messages through; nil types every message.
	Input   Input
	Uploads Uploads
	// Refs names the designs a message points at; nil refuses a design reference (unsupported), the other kinds need none.
	Refs  Refs
	Clock Clock
	Log   Logger
	// Store keeps the conversations and the op answers; nil keeps nothing (tests).
	Store *Store
	// Handoffs keeps private full-history and oversized-text artifacts; nil does not support those handoffs.
	Handoffs *handoff.ArtifactStore
	// Moves names the conversations moved to another machine, which take no more messages; nil names none.
	Moves Moves
	// Source opens a conversation's transcript; nil reads the files of internal/transcript.
	Source func(c wire.Conversation) feed.Source
	// Closer closes the pane and tab of a deleted conversation; nil leaves them.
	Closer Closer
	// Background is where the background tasks come from; nil knows none.
	Background Background
	// Meta reads the effort and the goal off a Claude transcript; nil knows none.
	Meta *sessionmeta.Reader
	// Transcripts reads what a Claude transcript gains once for the feed and the transcript's other readers; nil has
	// the feed read its transcript itself.
	Transcripts *transcriptindex.Index
	// Titler names a conversation from its first message and the agent's first answer, for an agent that wrote no title
	// of its own (Codex, or Claude before it did); nil never names one, and the first message stays the title.
	Titler func(p wire.Provider, firstMessage, firstAnswer string) (string, error)
	// Summarizer writes a few lines on what the agent did in a turn, from the person's message and the agent's replies
	// (never the tools' input or output); nil writes none, and the notification keeps the start of the answer.
	// provider and model are the ones SummaryModel picked, else the chat's provider and ""; the implementation takes its
	// cheap model for "".
	Summarizer func(p wire.Provider, model, message string, replies []string) (string, error)
	// SummaryModel is the setting of the summaries' model; nil is «Авто».
	SummaryModel func() *wire.NoticeSummaryModel
	// Worktree makes a git worktree for a conversation and returns its folder; nil: a git worktree off the HEAD of the
	// repository the folder is in (a folder that is none is used as it is).
	Worktree func(cwd, name string) (string, error)
	// Shots reads the pictures the agent and its subagents looked at off a Claude transcript; nil knows none.
	Shots *shots.Reader
	// PictureRoots are the folders, besides a conversation's own, a picture its messages name may be shown from (Claude's
	// scratchpads, the uploads); nil shows none, the conversation's folder included.
	PictureRoots []string
	// PaneLinks names the services whose links the right pane tells apart. With it a conversation's snapshot and
	// channel carry what the pane reads of it (wire.Pane); nil sends none, and the page reads it by itself.
	PaneLinks *sources.Links
	// Models are the models an agent CLI takes; nil knows none, and the model command then trusts the id's shape.
	Models func(p wire.Provider) []wire.AgentModel
	// Profiles are the backend profiles (Kimi, GLM, Grok) a conversation may run on; nil knows none, and a conversation
	// asked to start on one is refused.
	Profiles Profiles
	// SessionAccount is told the backend profile a session of the agent runs on, once the session is known: the report
	// of spend counts the session to that account. nil tells nobody; a conversation on the CLI's own sign-in is not told.
	SessionAccount func(p wire.Provider, agentSessionID, profile string)
	// AgentSession finds a session the agent CLI kept; nil knows none, and a conversation cannot then be opened on one.
	AgentSession func(p wire.Provider, sessionID string) (AgentSession, bool)
	// FolderGone tells a folder that is no more (removed, or not a folder): a conversation asked to start in one is
	// refused{not-found} at once, and its first message stays with the person (GitHub #108). A folder that does not
	// answer (a network disk that hangs) is refused{timeout} as soon as the check gives up, not after the command's
	// whole budget. "" is a folder that is there; nil checks none.
	FolderGone func(dir string) wire.RefuseCode
	// DefaultCwd is the folder a new conversation starts in when the person names none: it goes to the page with the
	// projects. Empty offers none.
	DefaultCwd string
	Limits     wire.Limits
	// Terminals end the conversations' terminals; nil: terminal.stop is refused{unsupported} and nothing is stopped
	// for standing idle.
	Terminals Terminals
	// Index keeps the messages of the conversations for search; nil: nothing is searched.
	Index *msgindex.Index
	// Digest cuts another conversation to about budget characters for a message that points at it (wire.RefChat); nil:
	// such a reference is refused (unsupported).
	Digest func(ctx context.Context, conv string, budget int) (wire.ChatDigest, error)
	// ExportDir is where a conversation is written whole as Markdown for another agent to read; empty: no digest.
	ExportDir string
	// IdleStop is after how long without work a chat's terminal is stopped by itself, read at every sweep; nil or 0
	// never.
	IdleStop func() time.Duration
	// IdleFloor is after how long without activity a Claude chat's terminal is stopped whatever IdleStop says and
	// whoever has the chat open, read at every sweep (life.go, idleWindows); nil or 0: no floor.
	IdleFloor func() time.Duration
	// MemoryShort says the machine is short of memory now, and PressureStop is the floor that holds while it is
	// (0: none). Either nil: memory changes nothing.
	MemoryShort  func() bool
	PressureStop func() time.Duration
	// LegacyLife gives the chats' sessions back to the keepers of the agent tabs (life.go): the tabs' idle sleep and
	// startup resume act on chats too, and the layouts restore their sessions at a start.
	LegacyLife bool
	// Rewinder binds a rewound chat to its new session and keeps the folder's snapshots; nil (or no Terminals): rewind
	// is refused{unsupported}.
	Rewinder Rewinder
	// AutoContinue says which of the runtime's own continuations are on, read each time one is due: after a usage
	// limit resets, after a restart cut a turn short. nil: both on.
	AutoContinue func() (limit, restart bool)
	// Window is the window the agent itself reports for a session — its statusline for Claude, the transcript's
	// model_context_window for Codex — and the tokens its last answer was asked with (0 where it says nothing). nil: the
	// window is guessed from the model id.
	Window func(p wire.Provider, sessionID, transcriptPath string) (used, limit int64)
	// Cost is what a session cost by the agent's own count, in USD (Claude's statusline); 0 where it says nothing. nil:
	// never known.
	Cost func(p wire.Provider, sessionID string) float64
	// Compact is what the agent is set to compact at in a chat of the folder on the model, by its settings: Claude's
	// autoCompactWindow (window, the window it counts compaction from) and Codex's model_auto_compact_token_limit (at,
	// the tokens it compacts at); 0 where nothing is set. nil: nothing is ever set.
	Compact func(p wire.Provider, cwd, model string) (window, at int64)
	// LimitReset is when the provider's usage limit resets by the limits it last reported — the window it ran out of —
	// for a notice that names no time; 0 when they say nothing. nil: never known.
	LimitReset func(p wire.Provider, now time.Time) wire.Ms

	// TerminalOff says that the machine's policy keeps the terminal off for the hub; nil: it is on. While it is, a
	// message that would start Claude's bash mode ("!…") is refused{forbidden}, and one queued earlier is not typed
	// (see internal/chatguard, which also guards the pane the typist writes to).
	TerminalOff func() bool

	// AppsOK checks the apps a conversation is asked to turn on: each installed on this machine and working in a chat.
	// It answers the id of the first that is not, or "". nil: no app can be turned on (refused{unsupported}).
	AppsOK func(ids []string) string

	// AppsLive says whether the running agent of a conversation takes its apps changed to ids as it runs: the
	// tools of the apps it did not start with come to it live, their words on its next turn. false (or nil) stops an
	// agent at rest, and the next message brings it back with the apps.
	AppsLive func(rec wire.Conversation, ids []string) bool

	// AlwaysApps are the apps a new chat starts with: the installed ones that ask to be on in every chat. nil or
	// empty: a new chat has none.
	AlwaysApps func() []string

	// Notify hears what a chat's agent did that the person is told of or that is kept for later: the end of a turn
	// (Notice*), a question or permission it waits on. Called on the conversation's actor, so it must not block; nil
	// tells nobody.
	Notify func(n Notice)
	// contains filtered or unexported fields
}

Deps is what a Runtime is built on.

type Hook

type Hook struct {
	// Kind: session-start, prompt-submit, notification, stop, stop-failure, pre-compact, post-compact.
	Kind string
	// Notification is the notification's type (permission_prompt, idle_prompt, …).
	Notification string
	// Failure is what a stop-failure says went wrong.
	Failure wire.TurnFailureCode
	// PromptHash of a prompt-submit names the prompt the agent took, "" when the hook did not say.
	PromptHash string
}

Hook is one of the agent's hooks, as POST /api/status/hook carries it.

type ImportTab

type ImportTab struct {
	ID      string
	Session string
	// Title is what names the tab's conversation: the agent's title of the transcript, its summary, the last message,
	// the first that is there. The tab's own title and name are not in it: they are what the terminal shows (the
	// agent's process, the folder), not what the chat is about. A conversation with none is named by its first message.
	Title string
	// Pane is the tab's terminal title, kept only to recognise it as a name an earlier import took by mistake.
	Pane string
	// Name is the tab's own name, "Claude Code" until the person renames it.
	Name           string
	Provider       wire.Provider
	Cwd            string
	TranscriptPath string
	AgentSessionID string
	CreatedAt      wire.Ms
	// LaunchUltracode: the tab was started with --effort ultracode. Claude's transcript logs it as xhigh.
	LaunchUltracode bool
	// Apps are the apps the tab's launch started with (its meta's launch.apps): the conversation keeps them on, so a
	// relaunch and the chat's switches see what the agent runs with.
	Apps []string
	// From is the app that started the tab's chat for the person (its meta's from), with the chat's title.
	From *wire.ChatFrom
}

ImportTab is a Legacy tab that runs an agent.

func TabFromLayout

func TabFromLayout(tab *jsvalue.Object, cwd, metaKey string) (ImportTab, bool)

TabFromLayout reads a tab object of a Legacy workspace layout (state.TabFromLayout's fields); ok is false for a tab that runs no agent or has no usable id. metaKey is the tab field the platform keeps its metadata in (the launch with its apps); "" reads none.

type Input

type Input interface {
	Send(ctx context.Context, conv wire.Conversation, m InputMessage) error
}

Input is the agents' structured channel: a message handed over it is a record with the client's id, and the agent's own protocol says it has it — nothing is typed and no screen is read. Send returns nil once the agent has the message. ErrInputUncertain: it may have it, and only the transcript can say. Any other error: it does not, and the message is typed in the terminal as before.

type InputMessage

type InputMessage struct {
	ClientID string
	Text     string
	Images   []string
	// Steer puts the message into the turn that runs.
	Steer bool
}

InputMessage is a message for Input: ClientID is the message's own id, the same at every try.

type Interrupter

type Interrupter interface {
	Interrupt(ctx context.Context, conv wire.Conversation) error
}

Interrupter is an Input that stops the conversation's running turn itself, instead of an Escape in its terminal.

type LaunchRequest

type LaunchRequest struct {
	ID       string
	Cwd      string
	Provider wire.Provider
	Model    *wire.Model
	// ResumeSessionID starts the agent on a session it kept (the model stays the session's own); TranscriptPath is that
	// session's transcript, which the conversation already shows.
	ResumeSessionID string
	TranscriptPath  string
	// Fork starts the agent on a fork of ResumeSessionID made by its CLI (Codex's `fork`): a session of its own with the
	// other's history, found as a fresh one's is. TranscriptPath is "" then.
	Fork bool
	// First is the text the agent starts with as its first prompt (a message the conversation carries by the launch,
	// never typed); "" for none.
	First string
	// Apps are the apps on in the conversation, which its agent starts with (internal/apps); Claude Code and Codex.
	Apps []string
}

LaunchRequest is a conversation to start.

type Launcher

type Launcher interface {
	Launch(req LaunchRequest) error
	// Resume starts a stopped agent again on its session.
	Resume(conv wire.Conversation) error
}

Launcher starts agents. Its calls return at once; the steps, the ready and the failure come back through Runtime.Launch*.

type LegacyProject

type LegacyProject struct{ ID, Name string }

LegacyProject is a project of Legacy's organizer: a name over a free group of conversations.

func LegacyOrganizer

func LegacyOrganizer(file string) ([]LegacyProject, map[string]string, error)

LegacyOrganizer reads Legacy's organizer file: its projects, and conversation id → project for the conversations of agent tabs (`agent:<machine>:<tab>` or `agent:<tab>`; the tab is the conversation). A missing file is none.

type Logger

type Logger interface {
	Info(msg string, kv ...any)
	Warn(msg string, kv ...any)
}

Logger is where the actors write what a person reading the journal needs.

type Machine

type Machine interface {
	// Pane is the agent pane of a tmux session, nil when the session has none.
	Pane(session string) typist.Pane
	// Probe is what runs in the session now.
	Probe(session string) Probe
}

Machine is the conversations' panes and processes.

type ModeKeeper

type ModeKeeper interface {
	KeepModes(session string, fast bool, permission wire.PermissionMode)
}

ModeKeeper is a Launcher that keeps the fast and permission modes a chat last ran in on its tab, so the next start of its agent, the runtime's own resume at startup too, starts in them again.

type MoveInfo added in v0.16.5

type MoveInfo struct {
	Title string
	Cwd   string
	// Busy: the agent works or waits for an answer; a conversation moves at rest.
	Busy bool
	// HasHistory: the agent has written a transcript.
	HasHistory bool
}

MoveInfo is what a move reads of a conversation.

type MoveOpen added in v0.16.5

type MoveOpen struct {
	Title    string
	Cwd      string
	History  []byte
	Provider wire.Provider
	Profile  string
	Model    string
	Effort   string
}

MoveOpen starts the conversation of a move: a new native session in cwd whose first prompt points at the history, held in a private file the first turn's end removes. The conversation names no other: it came from nowhere.

type Moves added in v0.16.5

type Moves interface {
	Blocked(conv string) bool
}

Moves says which conversations were moved to another machine: a conversation it blocks takes no more messages, because its work goes on elsewhere. nil blocks none.

type Notice

type Notice struct {
	Kind NoticeKind
	Conv wire.Conversation
}

Notice is one thing a chat's actor tells Deps.Notify, with the record as it stands right after it.

func (Notice) Push

func (n Notice) Push() bool

Push says the notice is one the person gets on their devices. A delegated chat works unheard: it reaches the person only when it waits for them (a question, a permission, a plan); its finished or failed turns go to its parent agent.

type NoticeKind

type NoticeKind string

NoticeKind is what a Notice tells.

const (
	// NoticeDone: the agent ended its turn and waits for the person (its Stop).
	NoticeDone NoticeKind = "done"
	// NoticeFailed: the turn ended with an error (StopFailure).
	NoticeFailed NoticeKind = "failed"
	// NoticeQuestion: the agent waits on a question, a permission or a plan.
	NoticeQuestion NoticeKind = "question"
	// NoticeTurnEnded: a turn ended however it ended (done, failed, stopped by the person, gone quiet); the folder's
	// snapshot for the rewind is taken on it.
	NoticeTurnEnded NoticeKind = "turn-ended"
	// NoticeState: the agent's state changed (setState); the tab keeper's view of the chat follows it.
	NoticeState NoticeKind = "state"
)

type PaneSample

type PaneSample struct {
	// Root is the pane's own process (its shell).
	Root int
	// Procs are every process of the tree, Root included.
	Procs []Proc
}

PaneSample is the process tree under a pane at one moment.

type PeerOutcome

type PeerOutcome struct {
	Where  PeerWhere
	Reason wire.QueueReason
}

PeerOutcome is what became of a message from another agent.

type PeerWhere

type PeerWhere string

PeerWhere is where a message from another agent stands.

const (
	// PeerInTurn: the agent has it inside its running turn (typed in, read at its next step, or read already).
	PeerInTurn PeerWhere = "in-turn"
	// PeerStarted: the agent was free and took it as a new turn.
	PeerStarted PeerWhere = "started"
	// PeerQueued: it waits in the line; Reason says for what.
	PeerQueued PeerWhere = "queued"
	// PeerFailed: it will not be delivered (failed, cancelled, unknown).
	PeerFailed PeerWhere = "failed"
)

type PermissionAsk added in v0.16.86

type PermissionAsk struct {
	Tool        string
	Input       json.RawMessage
	Suggestions json.RawMessage
	Cwd         string
}

PermissionAsk is what a hook asks: the tool, its input as the agent gave it, Claude's suggested rules for «don't ask again» (nil when there are none), the folder.

type PermissionReply added in v0.16.86

type PermissionReply struct {
	Behavior           string          `json:"behavior"`
	UpdatedInput       json.RawMessage `json:"updatedInput,omitempty"`
	UpdatedPermissions json.RawMessage `json:"updatedPermissions,omitempty"`
	Message            string          `json:"message,omitempty"`
	Interrupt          bool            `json:"interrupt,omitempty"`
}

PermissionReply is the `decision` of the hook's output.

type Phase

type Phase string

Phase is where a chat's terminal stands.

const (
	PhaseCold Phase = "cold"
	PhaseWarm Phase = "warm"
	PhaseHot  Phase = "hot"
)

func PhaseOf

func PhaseOf(k wire.AgentStateKind) Phase

PhaseOf reads the phase off an agent state. A state not looked at yet (unknown, after a start) and a launch on its way count as warm: a session may be there, and nothing ends it before a look says what it holds.

type Probe

type Probe struct {
	// Session: the tmux session exists.
	Session bool
	// Foreground: the agent CLI, not a shell, is in the pane's foreground.
	Foreground bool
	// Shell: a bare shell is in the foreground (the agent exited).
	Shell bool
	// Resumable: the agent has a session to start again on.
	Resumable bool
	// HandOver: the running tool can be handed to the background (Claude: Bash, an MCP call).
	HandOver bool
}

Probe is the process under a session's pane.

type Proc

type Proc struct {
	PID, PPID int
	// Comm is the process's name (/proc/<pid>/comm), Argv its command line.
	Comm string
	Argv []string
	// CPU is the processor time it has used so far (user and system).
	CPU time.Duration
	// RSS is its resident memory in bytes.
	RSS int64
}

Proc is one process of a pane's tree as /proc tells it.

type Profiles added in v0.15.46

type Profiles interface {
	// Lookup says which CLI a profile runs through, whether a key is saved for it and which models it has; ok is false
	// for a profile the machine does not know.
	Lookup(id string) (via wire.Provider, configured bool, models []string, ok bool)
	// Model is the capability record a choice's effort is checked against.
	Model(profile, model string) (wire.AgentModel, bool)
	// OwnsModel says whether the id is a model of some profile, configured or not. A conversation on the CLI's own account
	// is not started on it or switched to it unless that account lists the id too (Deps.vendorOnly): Codex signed in with
	// ChatGPT has the ids of the built-in GPT profile as its own.
	OwnsModel(model string) bool
	// Window is the context window of a model of the profile, in tokens; 0 when the profile or the model is not known.
	Window(profile, model string) int
}

Profiles knows the backend profiles: another vendor's models behind an agent CLI. A conversation runs on one from its start to its end; the profile is on its record as Model.Profile.

type Publisher

type Publisher interface {
	Publish(ch wire.Channel, e wire.Event) (seq int64)
}

Publisher takes the events of the actors in order and gives each its seq on its channel.

type Refs

type Refs interface {
	// Line is the agent's line for r, said of conversation conv; a refuse code when r is not there (not-found).
	Line(conv string, r wire.MessageRef) (string, wire.RefuseCode)
}

Refs describes the places a message points at that only the machine knows how to name (a design of the library), and notes that the conversation points at them (the design lists the chat among its own).

type Rewinder

type Rewinder interface {
	// Bind makes the chat's tab resume on the agent session sessionID, whose transcript is at transcript.
	Bind(c wire.Conversation, sessionID, transcript string) error
	// Snapshot is the newest snapshot of the chat's folder taken in [from, to]; false when there is none.
	Snapshot(c wire.Conversation, from, to wire.Ms) (Snapshot, bool)
	// Changes is what returning the folder to s changes: at most wire.RewindChangesMax of the files, and how many more.
	Changes(s Snapshot) ([]wire.RewindChange, int, error)
	// Restore returns the folder to s, after a snapshot of it as it is (which an undo returns to).
	Restore(s Snapshot) (before Snapshot, err error)
}

Rewinder binds a chat's tab to another session of its agent and keeps the snapshots of the chat's folder.

type Runtime

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

Runtime is the conversations of one runtime: an actor per conversation and the op answers. It implements Service.

func New

func New(d Deps) *Runtime

New is a runtime on d. Start loads what the store holds and starts the actors.

func NewInline

func NewInline(d Deps) *Runtime

NewInline is a runtime whose actors run on the caller's goroutine (tests).

func (*Runtime) Advance

func (r *Runtime) Advance()

Advance runs every actor's clock turn and look: what the runner does every LookEvery (tests drive it).

func (*Runtime) Attach

func (r *Runtime) Attach(id, session, transcriptPath, agentSessionID string) error

Attach names the tmux session and the transcript of a conversation once the launcher knows them. What it is not told ("" for the transcript or the agent's session) stays as it was.

func (*Runtime) AttachedSessions

func (r *Runtime) AttachedSessions() map[string]string

AttachedSessions are the agent sessions the conversations hold, by the agent's own session id.

func (*Runtime) Busy

func (r *Runtime) Busy() int

Busy is how many conversations have an agent at work, from what each actor left after its last turn.

func (*Runtime) ChatDigest added in v0.15.46

func (r *Runtime) ChatDigest(ctx context.Context, id string, budget int) (wire.ChatDigest, error)

ChatDigest cuts a conversation to about budget characters: its title, the first request, and the latest messages that fit, the last answer among them; the whole of it is written as Markdown to a file the agent may read.

func (*Runtime) ChatGlance

func (r *Runtime) ChatGlance(ctx context.Context, id string) (wire.ChatGlance, error)

ChatGlance gives the newest message of each side of a conversation, cut short, and how many messages the index holds for it. Unlike ChatDigest it writes nothing.

func (*Runtime) Context

func (r *Runtime) Context(ctx context.Context, id string) (wire.ConvContext, error)

Tasks is the agent's task list of a conversation, in the order the tasks were made. Context is how full the agent's window is: the tokens its last answer was asked with, of its model's window.

func (*Runtime) ConvOfSession

func (r *Runtime) ConvOfSession(session string) string

ConvOfSession is the conversation that runs in a tmux session, "" for none.

func (*Runtime) Conversation

func (r *Runtime) Conversation(ctx context.Context, id string) (wire.ConvSnapshot, error)

func (*Runtime) ConversationAfter

func (r *Runtime) ConversationAfter(ctx context.Context, id, afterEntryID string) (wire.ConvSnapshot, error)

func (*Runtime) Conversations

func (r *Runtime) Conversations(ctx context.Context) (wire.ConvsSnapshot, error)

func (*Runtime) DeliverPeer

func (r *Runtime) DeliverPeer(ctx context.Context, convID, clientID, text string, steer bool) wire.CmdResult

DeliverPeer puts a message from another agent into the queue of convID. With steer it goes into the running turn, read at the agent's next step (DeliverPeerAtOnce: at once), and, when no turn runs or the agent cannot take it now (it asks for a permission or asks the person a question, it compacts, its box holds someone's text), it waits at the head of the line and goes in as soon as the agent can take it. Without steer it waits at the head of the line for the turn to end. The answer is the send's own result; PeerOutcome says where the message went.

func (*Runtime) DeliverPeerAtOnce

func (r *Runtime) DeliverPeerAtOnce(ctx context.Context, convID, clientID, text string) wire.CmdResult

DeliverPeerAtOnce is DeliverPeer steered and urgent: in a running turn the tool the agent runs is handed to the background, so the message is read now and not when that tool ends (outbox.Record.Soft). It is this machine's own delegation that may ask for it — a message from another machine never does: its id and text are its sender's, and neither can carry the mark.

func (*Runtime) DeliverRoutine

func (r *Runtime) DeliverRoutine(ctx context.Context, convID, runID, text string) wire.CmdResult

DeliverRoutine puts a routine's run into the line of convID. It never goes into a running turn: it waits behind what the person queued, and the agent takes it as a turn of its own. Like another agent's message, it never answers a question the agent asked the person.

func (*Runtime) Delivered added in v0.16.86

func (r *Runtime) Delivered(ctx context.Context, id, path string) (string, bool, error)

Delivered is the sha256 of the file at this path as the agent handed it over in this conversation (deliver_file).

func (*Runtime) Do

func (r *Runtime) Do(ctx context.Context, device string, cmd wire.Command) wire.CmdResult

Do answers a command once per opId: the same body gets the same answer for OpsKept, another body conflict. It answers within the budget; a command still running then answers refused{timeout}, and its retry waits for the first one's answer.

func (*Runtime) EntryOutput

func (r *Runtime) EntryOutput(ctx context.Context, id, entryID string) (wire.OutputPage, error)

func (*Runtime) Epoch

func (r *Runtime) Epoch() string

Epoch is new on every start of the runtime.

func (*Runtime) Excerpt

func (r *Runtime) Excerpt(id string, provider wire.Provider, model, profile string) (wire.HandoffDraft, error)

Excerpt is the draft of a handoff by excerpt: the conversation's context within the budget of the model it goes to (provider "" is the conversation's own agent).

func (*Runtime) Has

func (r *Runtime) Has(id string) bool

Has tells whether the runtime holds a conversation (a deleted one too, until it is purged).

func (*Runtime) HasAttachment

func (r *Runtime) HasAttachment(ctx context.Context, chat, upload string) bool

HasAttachment checks an upload against this chat's persisted outbox, including messages already delivered.

func (*Runtime) History added in v0.16.5

func (r *Runtime) History(id string) (wire.HandoffDraft, error)

History snapshots every complete JSONL record without loading the transcript into the feed or requiring an agent session. The destination id is reserved server-side and recovered from the opaque artifact when it is sent.

func (*Runtime) Hook

func (r *Runtime) Hook(id string, h Hook) error

Hook feeds a hook to its conversation: the transcript is read first, so the entry the hook is about is there.

func (*Runtime) Import

func (r *Runtime) Import(tabs []ImportTab, queues map[string][]outbox.LegacyItem) int

Import takes Legacy's tabs and their queues: each tab not known yet becomes a conversation, unknown until its probes say more, its queue in order. Importing twice changes nothing.

func (*Runtime) ImportProjects

func (r *Runtime) ImportProjects(projects []LegacyProject, assign map[string]string) int

ImportProjects takes over Legacy's projects: each becomes a v2 project under its id and name, at the folder most of its conversations work in, and its conversations go into it. Legacy's projects are groups: several of them in one folder stay several. assign is conversation id → Legacy project id. A conversation is put into its project once: what the person does in v2 afterwards stays.

func (*Runtime) Index added in v0.15.46

func (r *Runtime) Index() *msgindex.Index

Index is the search index the runtime keeps (nil without one).

func (*Runtime) Indexing added in v0.15.46

func (r *Runtime) Indexing() bool

Indexing reports whether the scan has not yet read every conversation.

func (*Runtime) InputLost

func (r *Runtime) InputLost(id string)

InputLost: the conversation's structured channel ended. The turn ends are the hooks' to tell again; the next message tries the channel anew.

func (*Runtime) InputReady

func (r *Runtime) InputReady(id string)

InputReady: the conversation's structured channel connected, so queued/steered messages can be sent over it again.

func (*Runtime) InputTurnEnded

func (r *Runtime) InputTurnEnded(id string, failed bool, detail string) error

InputTurnEnded is the end of a turn as the conversation's structured channel tells it: failed says the turn ended on an error, detail what the agent said of it.

func (*Runtime) InputTurnStarted

func (r *Runtime) InputTurnStarted(id string) error

InputTurnStarted is the start of a turn as the conversation's structured channel tells it (e.g. Antigravity ACP bridge): moves the conversation into working so the sidebar spinner and transcript polling stay active immediately.

func (*Runtime) LaunchFailed

func (r *Runtime) LaunchFailed(id string, f wire.LaunchFailure)

func (*Runtime) LaunchMode

func (r *Runtime) LaunchMode(id string, mode wire.PermissionMode)

LaunchMode is the permission mode the launcher started a conversation's agent in, chosen or the machine's default of that start: the record says it (wire.Conversation.RunsIn), so a default changed later does not read as the mode of the session that runs (GitHub #124).

func (*Runtime) LaunchReady

func (r *Runtime) LaunchReady(id string)

func (*Runtime) LaunchStep

func (r *Runtime) LaunchStep(id string, step wire.LaunchStep)

LaunchStep, LaunchReady and LaunchFailed are what the launcher reports of a conversation it starts.

func (*Runtime) Loaded

func (r *Runtime) Loaded() int

Loaded is how many conversations have an actor now, Parked how many are held by their record alone.

func (*Runtime) MessageStatus added in v0.15.46

func (r *Runtime) MessageStatus(ctx context.Context, id string, ids []string) (wire.MessageStatuses, error)

MessageStatus is the conversation's word on its messages by their client ids, one per id in order: known (the record and where a typed message went), unknown, or expired (its record let go long ago).

func (*Runtime) MoveDelete added in v0.16.5

func (r *Runtime) MoveDelete(id string)

MoveDelete removes a conversation a move made and then undid; it is idempotent and takes nothing else.

func (*Runtime) MoveFence added in v0.16.5

func (r *Runtime) MoveFence(id string) (string, bool)

MoveFence is a token that changes when the conversation's transcript does: the size it has now.

func (*Runtime) MoveIDs

func (r *Runtime) MoveIDs() []string

MoveIDs are the conversations of the runtime, read without waking any (the resume snapshots look at them).

func (*Runtime) MoveInfo added in v0.16.5

func (r *Runtime) MoveInfo(id string) (MoveInfo, bool)

MoveInfo reads the conversation a move starts from.

func (*Runtime) MoveOpen added in v0.16.5

func (r *Runtime) MoveOpen(in MoveOpen) (string, wire.RefuseCode)

MoveOpen starts it; the id is the new conversation's.

func (*Runtime) MoveSnapshot added in v0.16.5

func (r *Runtime) MoveSnapshot(id string, max int64) ([]byte, string, error)

MoveSnapshot is the conversation's whole history as provider-neutral JSONL, read once and left nowhere on this machine, and the fence it was read at. Larger than max bytes is refused.

func (*Runtime) OwnsSession

func (r *Runtime) OwnsSession(session string) bool

OwnsSession says the tmux session is a chat's, so its life is decided here and by nobody else. Always false with Deps.LegacyLife.

func (*Runtime) Parked

func (r *Runtime) Parked() int

func (*Runtime) PeerOutcome

func (r *Runtime) PeerOutcome(ctx context.Context, convID, clientID string, wait time.Duration) PeerOutcome

PeerOutcome waits, at most wait, until the message clientID of convID is with the agent or is held in the line for a reason that will not pass by itself in a moment, and says which. A message still being typed when the wait ends is reported as queued behind a busy agent: it is on its way and is never typed twice.

func (*Runtime) PermissionRequest added in v0.16.86

func (r *Runtime) PermissionRequest(ctx context.Context, id string, ask PermissionAsk) (PermissionReply, bool)

PermissionRequest opens the person's card for what the agent's hook asks and waits for the decision. false, at any time, leaves it to the agent's own dialog: the gate ended some other way, the hook went, nothing is to be asked here.

func (*Runtime) Phase

func (r *Runtime) Phase(id string) (Phase, bool)

Phase is the phase of a conversation as its actor last left it; false for one the runtime does not have.

func (*Runtime) PicturePath

func (r *Runtime) PicturePath(ctx context.Context, id, picture string) (string, []string, error)

PicturePath is the file of a picture the conversation's messages name, as its snapshot lists it, and the folders it may be shown from: the file is checked against them again when it is opened. An id it does not list is wire.ErrNoShot.

func (*Runtime) Plan

func (r *Runtime) Plan(ctx context.Context, id, entryID string) (wire.RewindPlan, error)

Plan is what a rewind to the person's message entryID would do (wire.RewindSource).

func (*Runtime) Project added in v0.16.154

func (r *Runtime) Project(id string) (wire.Project, bool)

Project returns local project metadata without entering a conversation actor.

func (*Runtime) ProjectList

func (r *Runtime) ProjectList() []wire.Project

ProjectList is the machine's projects now.

func (*Runtime) Reap

func (r *Runtime) Reap() []string

Reap is one sweep: it stops the terminals of the chats that stood idle for the whole window and returns their ids (the stops finish off the sweep's goroutine; the inline runtime of a test has finished them on return).

func (*Runtime) Record

func (r *Runtime) Record(id string) (wire.Conversation, bool)

Record is a conversation as its actor last left it, with its tmux session and folder; false for one the runtime does not have or that is deleted.

func (*Runtime) RetitleImported

func (r *Runtime) RetitleImported(t ImportTab)

RetitleImported gives a conversation taken over from Legacy the title Legacy shows for its tab. A title the person typed in v2 stays; so does one an earlier import took from the tab's name before titles were read this way.

func (*Runtime) Rewound

func (r *Runtime) Rewound(ctx context.Context, id string, n int) (wire.TurnsPage, error)

Rewound is the turns the conversation's rewind n left behind, by their faces (wire.RewindSource).

func (*Runtime) SearchMessages added in v0.15.46

func (r *Runtime) SearchMessages(_ context.Context, query string, limit int) (wire.MessageSearch, error)

SearchMessages finds the messages that hold the words of the query, in the conversations that are not deleted.

func (*Runtime) SessionSpare

func (r *Runtime) SessionSpare(session string) (spare, owned bool)

SessionSpare says whether a chat's session that holds nothing but its shell may be ended: the chat is cold with nothing waiting to be typed, so the session serves nobody and the resume makes it again. owned is false for a session that is no chat's (or with Deps.LegacyLife): the caller decides as it did.

func (*Runtime) ShotPath

func (r *Runtime) ShotPath(ctx context.Context, id, shot string) (string, error)

ShotPath is the file of a picture the conversation lists in its snapshot, and nothing else: an id it does not list is wire.ErrNoShot, whatever the caller meant.

func (*Runtime) Start

func (r *Runtime) Start(ctx context.Context) error

Start loads the conversations written before and starts their actors. Each comes back unknown and is probed; a message a restart caught on its way is settled by the screen and the transcript, never typed again blindly.

func (*Runtime) Stop

func (r *Runtime) Stop()

Stop ends the actors after each wrote its last state.

func (*Runtime) Tasks

func (r *Runtime) Tasks(ctx context.Context, id string) ([]wire.Task, error)

func (*Runtime) TerminalOutput added in v0.16.5

func (r *Runtime) TerminalOutput(session string, data []byte)

TerminalOutput gives the conversation the bytes its agent printed to its PTY. Unknown sessions are ignored.

func (*Runtime) Touched

func (r *Runtime) Touched(ctx context.Context, id, path string) (bool, error)

Touched is whether the conversation's agent wrote, edited or read the file at this path in one of its turns.

func (*Runtime) Transcripts

func (r *Runtime) Transcripts() []string

Transcripts are the agent transcripts of the conversations, as their actors last left them: read without asking an actor anything, so a reader beside the runtime (the design links' backfill) never wakes or holds one.

func (*Runtime) TurnEntries

func (r *Runtime) TurnEntries(ctx context.Context, id, turnID string) (wire.EntriesPage, error)

func (*Runtime) Turns

func (r *Runtime) Turns(ctx context.Context, id, beforeTurnID string, limit int) (wire.TurnsPage, error)

func (*Runtime) TurnsWithSteps

func (r *Runtime) TurnsWithSteps(ctx context.Context, id, beforeTurnID string, limit int) (wire.TurnsPage, error)

TurnsWithSteps is Turns with the steps of every turn of the page (wire.StepsPager).

func (*Runtime) Unload

func (r *Runtime) Unload() []string

Unload is one sweep: it parks the conversations at rest nobody asked for in UnloadAfter and returns their ids.

type SeqTeller

type SeqTeller interface {
	Seq(ch wire.Channel) int64
}

SeqTeller is a Publisher that tells a channel's last seq.

type Service

type Service interface {
	// Conversations is the data of a convs snapshot: every conversation not deleted, pinned ones first, then by
	// lastActivityAt, newest first.
	Conversations(ctx context.Context) (wire.ConvsSnapshot, error)

	// Conversation is the data of a whole conv:<id> snapshot. ErrNotFound for a conversation it does not have.
	Conversation(ctx context.Context, id string) (wire.ConvSnapshot, error)

	// ConversationAfter is the data of a conv:<id> snapshot with mode "after": the entries after afterEntryID and the
	// current queue, messages, gates, background and now. ErrUnknownCursor when the entry is not in the transcript;
	// the caller then sends a whole snapshot.
	ConversationAfter(ctx context.Context, id, afterEntryID string) (wire.ConvSnapshot, error)

	// Turns is the page of turns before beforeTurnID ("" from the end), at most limit, oldest first, with their
	// answer entries.
	Turns(ctx context.Context, id, beforeTurnID string, limit int) (wire.TurnsPage, error)

	// TurnEntries is every entry of one turn, for a turn opened in the feed.
	TurnEntries(ctx context.Context, id, turnID string) (wire.EntriesPage, error)

	// EntryOutput is the whole output of a tool entry.
	EntryOutput(ctx context.Context, id, entryID string) (wire.OutputPage, error)

	// Do runs a checked command for a device and answers it. The answer of an opId is kept for 24 hours: the same
	// opId with the same body gets it again, with another body refused{conflict}. An accepted or queued answer
	// names the channel and seq from which its effect shows; Do returns once that event is published, and always
	// within wire.Limits.CmdBudgetMs: what does not finish by then answers refused{timeout} and is safe to retry.
	Do(ctx context.Context, device string, cmd wire.Command) wire.CmdResult
}

Service is what the protocol asks of the conversations. Every method is safe to call from any goroutine; the answers are copies the caller may keep.

type SessionEnder

type SessionEnder interface {
	EndSession(session string)
}

SessionEnder is a Launcher that can end the tmux session of a launch that failed, with whatever still runs in it: a shell that hung before the agent started runs the launch line when it comes back, and that agent has no chat a launch made anew beside a session left alive gave one chat two agents.

type SessionForgetter

type SessionForgetter interface {
	ForgetScreen(session string)
	ForgetSession(session string)
}

SessionForgetter is a Machine that keeps something of every session it was asked about (the last probe, a capture of a tall dialog). ForgetScreen drops what it kept of the screen of a session whose terminal ended; ForgetSession drops everything, for a session nobody will look at again.

type Snapshot

type Snapshot struct {
	Tab string  `json:"tab"`
	Cwd string  `json:"cwd"`
	ID  string  `json:"id"`
	At  wire.Ms `json:"at"`
}

Snapshot is a snapshot of a chat's folder: which repository holds it (the tab and the folder) and its id.

type StartProber

type StartProber interface {
	ProbeAtStart(session string) Probe
}

StartProber is a Machine whose look at a start of the runtime is believed at once. Probe may take the first sight of a missing session for a passing moment and report the agent as still running; at a start, when tmux may have gone down with the runtime, that would keep a chat that was at work from being resumed.

type Store

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

Store keeps the runtime's v2 state under <data>/v2: one file per conversation, the op answers, the projects. Every write is the whole last state, through a temporary file, fsync and rename: a crash leaves the old file or the new one, never half of one.

func NewStore

func NewStore(dir string) *Store

NewStore is the store under dir (<data>/v2).

func (*Store) Async

func (s *Store) Async(onResult func(path string, fails int, err error))

Async makes the conversations' writes happen on a goroutine of the store's, the last state of a file winning. A write that failed stays with the store and is tried again after a pause that grows. onResult hears every failure with how many the file has had in a row, and (0, nil) once a file that had failed is written. Close ends it after the writes it holds.

func (*Store) Close

func (s *Store) Close() error

Close flushes within FlushWait and ends the writer; the error is the flush's.

func (*Store) CloseWithin

func (s *Store) CloseWithin(ctx context.Context) error

CloseWithin is Close with the caller's term.

func (*Store) Flush

func (s *Store) Flush(ctx context.Context) error

Flush returns once every write handed to the store has reached the disk, with nil. It gives the files that wait for a retry one more try, and returns an error when some still fail or when ctx ends first (a file system that hangs holds a write for good).

func (*Store) Fresh

func (s *Store) Fresh() bool

Fresh: the store holds nothing yet — the first start of v2, when the Legacy tabs and queue are imported.

type SystemClock

type SystemClock struct{ typist.SystemClock }

SystemClock is the wall clock.

func (SystemClock) After

func (SystemClock) After(d time.Duration) <-chan time.Time

type Terminals

type Terminals interface {
	// Owned: the session is the agent pane of a chat of this runtime, which it may end — never the session the runtime
	// itself runs in, nor one of a Legacy tab that is no chat, nor one of another program.
	Owned(session string) bool
	// Sample is the process tree under the session's pane now; false when it cannot be read.
	Sample(session string) (PaneSample, bool)
	// Watched: someone has the chat or its terminal open now (a page subscribed to the conversation, a terminal
	// attached to the pane).
	Watched(convID, session string) bool
	// Stop ends the agent and everything under the pane, then the tmux session, and returns once they are gone, with
	// the resident memory they held (0 when unknown).
	Stop(session string) (freedBytes int64, err error)
}

Terminals end the conversations' terminals and say what runs in them: terminal.stop and the idle stop (reap.go). Every call may touch tmux and /proc, so none runs on an actor.

type TextKeeper

type TextKeeper interface {
	Keep(name string, body []byte) (wire.AttachmentRef, string, bool)
}

TextKeeper is Uploads that can also keep a text the runtime wrote as a file of the message: a long message goes to the agent as a file, not a paste (attach.IsLongText). The ref and its path on the machine; false when it could not.

type TranscriptForgetter

type TranscriptForgetter interface {
	Forget(c wire.Conversation)
}

TranscriptForgetter is a Background that keeps a place in every transcript it read: Forget drops the one of a conversation that is deleted or whose actor was let go.

type Uploads

type Uploads interface {
	// Resolve is the attachments of ids and their paths on the machine, one per attachment; a refuse code when one is
	// missing or wrong.
	Resolve(ids []string) ([]wire.AttachmentRef, []string, wire.RefuseCode)
}

Uploads finds the files the page uploaded before it sent.

type Waker

type Waker interface {
	// Wakeup is when the pending wakeup comes (epoch ms); 0 when the agent has none.
	Wakeup(c wire.Conversation) wire.Ms
}

Waker is a Background that also knows the agent's own scheduled wakeup: the chat waits for it as for a task, but it is no task a person can open or stop.

Jump to

Keyboard shortcuts

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