agentcontrol

package
v1.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 19 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 agentcontrol owns provider-aware control of Sidecar-managed shells. It is transport-neutral: CLI and UI callers use the same service, while the local implementation speaks tmux through Terminal.

Index

Constants

View Source
const DetectionScrollback = 80

DetectionScrollback is how much history the lifecycle detector reads. It is stated once so `--source detection` returns the same slice the status verdict was computed from rather than a lookalike.

View Source
const PromptStallWindow = 5 * time.Second

PromptStallWindow is how long a prompt sent from a non-working state has to produce an observed lifecycle change before the caller is told the prompt stalled.

It is not a timeout on the agent's work — those are always the caller's explicit --timeout — but an honesty rule about the submission itself: an agent composer that swallowed the Enter, or a UI that is wedged, otherwise looks exactly like an agent that is thinking. Five seconds is long enough that no real provider misses it and short enough that a caller learns the prompt went nowhere before it starts waiting minutes for an answer.

Variables

This section is empty.

Functions

func AsError

func AsError(err error, target **Error) bool

func LogicalKeyVocabulary

func LogicalKeyVocabulary() []string

LogicalKeyVocabulary is the documented named-key allowlist.

func MarshalError

func MarshalError(err error) []byte

func ValidateKeys

func ValidateKeys(names []string) error

ValidateKeys reports whether every name in a logical-key sequence can be encoded, without touching a terminal. The CLI uses it to answer a typo as a usage error before it resolves a target or spawns tmux.

func WithPromptReceipt added in v1.14.0

func WithPromptReceipt(err error, target Target, submission SubmissionStatus, wait PromptWaitOutcome) error

WithPromptReceipt attaches the prompt's independently useful submission outcome to an existing operational error. target is the identity pinned for the write; an observation error may carry a different or absent target, but it cannot rewrite which occupant received the prompt.

Types

type Agent

type Agent struct {
	Target Target     `json:"target"`
	Agent  AgentState `json:"agent"`
	// Orphan is set on a worktree session that is still running after its
	// worktree was removed outside Sidecar (td-0b90da). The session is live, so
	// nothing else about it looks wrong; this is the only field that says the
	// directory it was started in is gone. `sidecar worktree prune-sessions`
	// closes it.
	Orphan *Orphan `json:"orphan,omitempty"`
}

Agent is the stable result shared by list, get, and start.

type AgentState

type AgentState struct {
	Kind             string    `json:"kind,omitempty"`
	Status           Status    `json:"status"`
	Freshness        string    `json:"freshness"`
	Attention        bool      `json:"attention"`
	Evidence         string    `json:"evidence,omitempty"`
	ChangedAt        time.Time `json:"changedAt,omitzero"`
	CapturedAt       time.Time `json:"capturedAt"`
	InteractiveReady bool      `json:"interactiveReady"`
	// SessionRef reports whether this shell is bound to an exact provider
	// conversation. It is absent when there is no binding.
	SessionRef *SessionRef `json:"sessionRef,omitempty"`
	// Candidate is a provider-store match for a shell without an exact reported
	// binding. Value, title, and reason follow SessionRef's redaction rule because
	// provider titles and explanatory alternatives may themselves contain IDs.
	Candidate *SessionCandidate `json:"candidate,omitempty"`
}

type Detector

type Detector func(Snapshot, *agentactivity.Tracker) AgentState

type Error

type Error struct {
	Code    ErrorCode `json:"code"`
	Message string    `json:"message"`
	Target  *Target   `json:"target,omitempty"`
	// Receipt is present for agent prompt failures. Other verbs keep their
	// existing envelope unchanged.
	Receipt *PromptReceipt `json:"receipt,omitempty"`
	Err     error          `json:"-"`
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string
const (
	ErrNotFound              ErrorCode = "agent_not_found"
	ErrPaneBusy              ErrorCode = "agent_pane_busy"
	ErrKindMismatch          ErrorCode = "agent_kind_mismatch"
	ErrNotReady              ErrorCode = "agent_not_ready"
	ErrStartFailed           ErrorCode = "agent_start_failed"
	ErrBlocked               ErrorCode = "agent_blocked"
	ErrPromptStalled         ErrorCode = "agent_prompt_stalled"
	ErrReplaced              ErrorCode = "agent_replaced"
	ErrTranscriptUnavailable ErrorCode = "transcript_unavailable"
	ErrTimeout               ErrorCode = "timeout"
	ErrTransport             ErrorCode = "transport_failed"
	ErrFeatureDisabled       ErrorCode = "feature_disabled"
	// ErrUsage is a command line the verb could not accept: a refused flag
	// combination, a missing argument. It exists so a --json caller reads the
	// refusal as the same envelope every other refusal arrives in, rather
	// than a prose line followed by the help text (td-a658ed).
	ErrUsage ErrorCode = "usage"
	// ErrHostUnavailable and ErrVersionSkew are M5 additions, and they exist
	// because a remote target has two failure modes the local vocabulary
	// cannot express without lying about them.
	//
	// A machine that is not reachable is not a transport that failed
	// mid-operation: nothing was attempted, retrying later is the fix, and
	// reporting transport_failed for it sends a reader looking for a fault
	// that is not there. And a host whose Sidecar does not know the verb
	// answers with a usage error — the exit-code contract's own capability
	// negotiation — where the fix is to update one of the two binaries and no
	// other code says so. Both keep the exit status the CLI already documents:
	// host_unavailable exits 1 with the other retryable failures, version_skew
	// exits 2, which agentExitCodes has always described as "usage error or
	// version skew".
	ErrHostUnavailable ErrorCode = "host_unavailable"
	ErrVersionSkew     ErrorCode = "version_skew"
)

type ErrorEnvelope

type ErrorEnvelope struct {
	Error *Error `json:"error"`
}

ErrorEnvelope is the machine stderr contract.

type KeysRequest

type KeysRequest struct {
	Target Target
	Keys   []string
}

type LocalTerminal

type LocalTerminal struct {
	Runner  Runner
	Paste   func(string, string) error
	Key     func(string, string) error
	Literal func(string, string) error
	Now     func() time.Time
	// contains filtered or unexported fields
}

func NewLocalTerminal

func NewLocalTerminal() *LocalTerminal

func (*LocalTerminal) Capture

func (t *LocalTerminal) Capture(ctx context.Context, snap Snapshot, req ReadRequest) (string, error)

Capture is the passive read. Each source is one capture-pane invocation and nothing else — no scrolling, no copy mode, no resize.

func (*LocalTerminal) Close

func (t *LocalTerminal) Close()

Close releases the control-mode pool. A caller that ran a wait must call it; a caller that only inspected may call it harmlessly.

func (*LocalTerminal) Inspect

func (t *LocalTerminal) Inspect(ctx context.Context, target Target) (Snapshot, error)

func (*LocalTerminal) Launch

func (t *LocalTerminal) Launch(ctx context.Context, snap Snapshot, argv []string) error

func (*LocalTerminal) SendKeys

func (t *LocalTerminal) SendKeys(ctx context.Context, snap Snapshot, names []string) error

SendKeys encodes the complete logical-key list before it writes anything. Validation precedes revalidation precedes the first byte: a caller answering a blocked agent's UI is never left having delivered part of a sequence.

func (*LocalTerminal) Signal

func (t *LocalTerminal) Signal(ctx context.Context, snap Snapshot) (<-chan Signal, func(), error)

Signal subscribes to the pooled control manager for one pinned pane.

Focused is set because the manager schedules captures only for a focused, visible subscription; it is not application focus and it moves nothing. Width and Height are deliberately left at zero: a sized subscription would issue `refresh-client -C`, and a headless command resizing the user's pane is the one thing an observer must never do.

func (*LocalTerminal) Submit

func (t *LocalTerminal) Submit(ctx context.Context, snap Snapshot, text string) error

Submit is the shared ordered text sender: revalidate the pinned pane, pass the exact text through tmux's bracketed-paste-aware buffer path, then submit Enter as a separate ordered key. The sequence itself is tty.PromptSteps, the same one the embedded terminal produces, so a headless prompt and a typed one deliver identical bytes.

type Orphan added in v1.15.0

type Orphan struct {
	// Reason is one of the shellliveness.Orphan* values:
	// worktree_not_in_git, worktree_prunable, or worktree_directory_missing.
	Reason string `json:"reason"`
	// Root is the removed worktree the session was started in.
	Root string `json:"root"`
}

Orphan explains why a live worktree session has no worktree behind it.

type PromptReceipt added in v1.14.0

type PromptReceipt struct {
	Submission SubmissionStatus  `json:"submission"`
	Wait       PromptWaitOutcome `json:"wait"`
	Target     Target            `json:"target"`
}

PromptReceipt is the additive prompt contract carried on success and error. Target is the identity pinned before submission; callers can decide whether a retry is safe without reconstructing identity from prose.

type PromptRequest

type PromptRequest struct {
	Target Target
	Text   string
	// Wait combines submission and settling under one pinned target so no
	// second command can race a replacement occupant into the gap.
	Wait bool
	// Until narrows or widens the accepted settled states. Empty means
	// DefaultSettledStates.
	Until []Status
	// Timeout is required when Wait is set. There is no implicit timeout.
	Timeout time.Duration
}

type PromptResult added in v1.14.0

type PromptResult struct {
	Target  Target        `json:"target"`
	Agent   AgentState    `json:"agent"`
	Receipt PromptReceipt `json:"receipt"`
}

PromptResult preserves Agent's top-level target/agent shape and adds the receipt, so existing JSON readers keep decoding the fields they know.

type PromptWaitOutcome added in v1.14.0

type PromptWaitOutcome string

PromptWaitOutcome describes the second half of `agent prompt --wait` without changing the command's established error code or exit status.

const (
	PromptWaitNotRequested PromptWaitOutcome = "not_requested"
	PromptWaitNotStarted   PromptWaitOutcome = "not_started"
	PromptWaitSettled      PromptWaitOutcome = "settled"
	PromptWaitTimeout      PromptWaitOutcome = "timeout"
	PromptWaitCancelled    PromptWaitOutcome = "cancelled"
	PromptWaitReplaced     PromptWaitOutcome = "replaced"
	PromptWaitStalled      PromptWaitOutcome = "stalled"
	PromptWaitFailed       PromptWaitOutcome = "failed"
)

type ReadRequest

type ReadRequest struct {
	Target Target
	Source ReadSource
	// Lines bounds the result. Zero means the source's own default.
	Lines int
	// ANSI preserves styling where the source has it. Terminal sources without
	// styling and the transcript ignore it.
	ANSI bool
}

ReadRequest is one passive read.

type ReadResult

type ReadResult struct {
	Target     Target              `json:"target"`
	Source     ReadSource          `json:"source"`
	Kind       string              `json:"kind,omitempty"`
	Status     Status              `json:"status,omitempty"`
	Lines      int                 `json:"lines"`
	CapturedAt time.Time           `json:"capturedAt"`
	Text       string              `json:"text,omitempty"`
	Messages   []TranscriptMessage `json:"messages,omitempty"`
}

ReadResult is the stable read contract.

type ReadSource

type ReadSource string

ReadSource names one passive view of a managed agent. Every terminal source is a capture: nothing here scrolls, resizes, enters copy mode, or otherwise touches the agent's own alternate-screen UI, because a read that changes what the agent is showing is a read that changed the thing it measured.

const (
	// SourceVisible is the pane's current screen, exactly as it stands.
	SourceVisible ReadSource = "visible"
	// SourceRecent is the visible screen plus recent scrollback.
	SourceRecent ReadSource = "recent"
	// SourceRecentUnwrapped is SourceRecent with soft wraps joined, which is
	// what makes logs and long agent answers usable as text.
	SourceRecentUnwrapped ReadSource = "recent-unwrapped"
	// SourceDetection is the exact slice the lifecycle detector reads, so a
	// caller arguing with a status verdict can see the evidence it saw.
	SourceDetection ReadSource = "detection"
	// SourceTranscript is the provider's own conversation, available only once
	// an exact provider-reported session binding exists.
	SourceTranscript ReadSource = "transcript"
)

func ParseReadSource

func ParseReadSource(value string) (ReadSource, error)

ParseReadSource accepts a source name from a caller.

func ReadSources

func ReadSources() []ReadSource

ReadSources lists the sources in the order the CLI documents them.

type ResumeRequest

type ResumeRequest struct {
	// Target is the managed shell to resume into.
	Target Target
	// Plan is the structured resume from agentsession.PlanResume. Callers do not
	// assemble Argv themselves; taking the plan whole is what keeps the kind, the
	// argv, and the reference they describe from drifting apart.
	Plan agentsession.ResumePlan
	// Timeout bounds the wait for the provider to identify itself and settle.
	// There is no implicit timeout; zero is refused.
	Timeout time.Duration
}

ResumeRequest asks for an exact conversation to be resumed in a managed shell.

There is no session-value field and no command string, only the validated Ref and the argv agentsession already built from it. That is the whole point of the type: a conversation identifier reaches a terminal exactly once, as a single argv element that was constructed by the provider catalog and never concatenated into anything a shell will parse.

type Runner

type Runner interface {
	Run(context.Context, ...string) ([]byte, error)
}

type Service

type Service struct {
	Terminal Terminal
	Now      func() time.Time
	// Poll is the bounded cadence used by start and by any watch whose terminal
	// offers no event stream.
	Poll           time.Duration
	ShellStableFor time.Duration
	// Observe is the minimum interval between full observations while a control
	// stream is delivering signals. It bounds what an output burst can cost:
	// without it, a coalesced control client can signal dozens of times a
	// second and each signal would buy two tmux processes.
	Observe time.Duration
	// Verify is how often a signalled watch re-reads the pane even when nothing
	// signalled. It is what makes a silent replacement, death, or copy-mode
	// entry unable to hold a wait open.
	Verify time.Duration
	// StallAfter is the PromptStallWindow, overridable for tests.
	StallAfter time.Duration
	// ShellInitGrace bounds how long waitShellReady will let an otherwise-live
	// pane finish initializing its interactive shell before Start refuses it.
	// It is still capped by the caller's own start timeout. Overridable for
	// tests. Zero means defaultShellInitGrace.
	ShellInitGrace time.Duration
	Detect         Detector
	// Transcript is nil until M3 binds an exact provider session. A nil reader
	// is a documented refusal, never a fallback to guessing.
	Transcript TranscriptReader
}

func (Service) Get

func (s Service) Get(ctx context.Context, target Target) (Agent, error)

func (Service) InspectState added in v1.15.0

func (s Service) InspectState(ctx context.Context, target Target) (Snapshot, AgentState, error)

InspectState is one inspect plus detection. Get and broadcast Plan share it so a fan-out does not pay two tmux captures per pane.

func (Service) Prompt

func (s Service) Prompt(ctx context.Context, req PromptRequest) (PromptResult, error)

Prompt submits text to a pinned managed agent, refusing before it writes any bytes if the target is not in a state that may receive input.

func (Service) Read

func (s Service) Read(ctx context.Context, req ReadRequest) (ReadResult, error)

Read returns a passive view of the target. It never scrolls, resizes, or otherwise manipulates the agent's own screen.

func (Service) SendKeys

func (s Service) SendKeys(ctx context.Context, req KeysRequest) (Agent, error)

SendKeys writes a validated logical-key sequence to a pinned managed agent. Every key is encoded before any of them is sent, so a caller answering a blocked agent's UI can never deliver half a sequence.

The validation is the service's, not the adapter's. The local tmux adapter re-encodes for its own writes and the CLI validates early to answer a typo without spawning anything, but neither of those is where the invariant can live: a second Terminal implementation — the remote host adapter this interface exists for — would otherwise be free to write a partial sequence and nothing above it would notice. Validating here means every adapter inherits it by construction.

func (Service) Start

func (s Service) Start(ctx context.Context, req StartRequest) (Agent, error)

func (Service) StartResume

func (s Service) StartResume(ctx context.Context, req ResumeRequest) (Agent, error)

StartResume launches a provider's native resume in a managed shell and returns only once that provider is positively identified and ready.

It is deliberately a thin composition over Start rather than a second launch path. Every rule Start enforces is a rule a resume needs at least as much: the pane must be occupied by its own interactive shell and nothing else, the occupant is pinned so a replacement cannot satisfy the wait, a different provider is a kind mismatch rather than a success, an early exit is a start failure, and blocked is reported as not-ready with the target left inspectable. A resume that invented its own readiness contract would be the one launch path in Sidecar that could report success into an empty pane.

What this adds is the refusal that belongs to resuming specifically: a plan whose reference was never vouched for by an official integration is rejected before any bytes are sent. agentsession.PlanResume already refuses to build such a plan, so this is a second check on the same rule at the boundary where the bytes would actually be written — worth having, because this function is callable with a hand-built plan and the cost of being wrong here is a provider resuming somebody else's conversation.

func (Service) Wait

func (s Service) Wait(ctx context.Context, req WaitRequest) (Agent, error)

Wait observes an already-running agent until it reaches one of the accepted states. It never writes to the pane.

func (Service) WaitShellReady

func (s Service) WaitShellReady(ctx context.Context, target Target, timeout time.Duration) (Snapshot, error)

WaitShellReady waits for a shell that the caller has just created and may still be seeding with Sidecar-owned setup commands. It pins the first live pane/server identity and never follows a replacement. Existing-target callers must use Start directly: its preflight refuses a foreground command rather than waiting for somebody else's work to finish.

type SessionCandidate added in v1.15.0

type SessionCandidate struct {
	Kind        string    `json:"kind,omitempty"`
	Value       string    `json:"value,omitempty"`
	Title       string    `json:"title,omitempty"`
	LastWriteAt time.Time `json:"lastWriteAt,omitzero"`
	Confidence  string    `json:"confidence"`
	Reason      string    `json:"reason"`
	Picker      bool      `json:"picker,omitempty"`
}

SessionCandidate is the stable agent-query projection of a recovery candidate. Reported is intentionally absent: candidates are never reports.

type SessionRef

type SessionRef struct {
	Kind     string `json:"kind,omitempty"`
	Reported bool   `json:"reported"`
	Value    string `json:"value,omitempty"`
}

SessionRef is what an agent query says about a shell's exact conversation binding.

Kind and Reported are capability and presence: they answer "can this shell be resumed, and did an official integration say so" without naming the conversation. Value is the conversation itself and is filled only for a caller's own shell or an explicit opt-in, because `agent list` output lands in logs, transcripts, and CI output, and a conversation identifier sprayed across those is not something a later decision to redact can take back.

type Signal

type Signal struct {
	Screen         string
	Title          string
	CurrentCommand string
	At             time.Time
}

Signal is one event-driven observation of a pinned pane, carrying only what the control stream can actually see.

type Signaler

type Signaler interface {
	Signal(ctx context.Context, snap Snapshot) (signals <-chan Signal, stop func(), err error)
}

Signaler is an optional Terminal capability: sustained, event-driven change notification for one pinned pane. A Terminal that does not implement it is observed by bounded polling instead, which is correct but costlier.

stop must release every client, subscription, and goroutine the call made. It is always called exactly once, including on cancellation and timeout.

type Snapshot

type Snapshot struct {
	Target
	Dead            bool
	CopyMode        bool
	PaneCount       int
	CurrentCommand  string
	ProcessIdentity string
	ShellReady      bool
	Title           string
	Screen          string
	// PaneHeight is the pane's row count, which is the manifest detection
	// engine's read window (agentactivity.Observation.PaneHeight).
	PaneHeight int
	CapturedAt time.Time
	// LaunchID is supplied to Launch and returned by Inspect only when that
	// exact launch has completed, including an exit too fast to observe.
	LaunchID string
}

Snapshot is one terminal observation. Identity fields are re-read on every observation so a wait cannot be satisfied by a replacement process.

type StartRequest

type StartRequest struct {
	Target  Target
	Kind    string
	Argv    []string
	Timeout time.Duration
}

type Status

type Status string
const (
	StatusUnknown Status = "unknown"
	StatusIdle    Status = "idle"
	StatusWorking Status = "working"
	StatusBlocked Status = "blocked"
	StatusDone    Status = "done"
)

func DefaultSettledStates

func DefaultSettledStates() []Status

DefaultSettledStates is what a wait accepts when the caller names nothing. working is deliberately absent: a wait that "succeeds" the moment an agent starts working is a wait nobody wanted.

func ParseStatus

func ParseStatus(value string) (Status, error)

ParseStatus accepts a status name from a caller.

func PromptableStates

func PromptableStates() []Status

PromptableStates are the states a prompt may be sent from.

type SubmissionStatus added in v1.14.0

type SubmissionStatus string

SubmissionStatus is the certainty Sidecar has about a prompt crossing the terminal boundary. Unknown is deliberate: a transport or terminal write can fail after applying input, and reporting either submitted or not_submitted in that case would invite an unsafe automatic retry.

const (
	SubmissionNotSubmitted SubmissionStatus = "not_submitted"
	SubmissionSubmitted    SubmissionStatus = "submitted"
	SubmissionUnknown      SubmissionStatus = "unknown"
)

type Target

type Target struct {
	Host      string `json:"host"`
	Project   string `json:"project"`
	Session   string `json:"session"`
	Name      string `json:"name,omitempty"`
	Namespace string `json:"namespace,omitempty"`
	PaneID    string `json:"paneId,omitempty"`
	PanePID   int    `json:"panePid,omitempty"`
	// ServerPID is the tmux server process, and it — not ServerIncarnation — is
	// what the occupant check compares.
	//
	// The incarnation string includes the socket's ctime, and tmux rewrites the
	// socket's permission bits whenever the set of attached clients changes
	// (server_update_socket). Attaching M2's own control-mode observer
	// therefore bumps the ctime, and an incarnation-based pin would report
	// every observed target as replaced the instant it began observing it. The
	// server pid answers the question the pin is actually asking — is this the
	// same server process? — and cannot drift because somebody attached.
	ServerPID int `json:"serverPid,omitempty"`
	// ServerIncarnation stays as observed evidence about the socket. It is
	// reported, not compared.
	ServerIncarnation string `json:"serverIncarnation,omitempty"`
}

Target is the pinned, host-shaped identity of one managed pane.

type Terminal

type Terminal interface {
	Inspect(context.Context, Target) (Snapshot, error)
	Launch(context.Context, Snapshot, []string) error
	// Submit sends exact prompt text followed by a separate submission key,
	// through the same ordered bracketed-paste path the embedded terminal uses.
	Submit(context.Context, Snapshot, string) error
	// SendKeys encodes every logical key name before writing any of them.
	SendKeys(context.Context, Snapshot, []string) error
	// Capture is a passive terminal read. It never manipulates the pane.
	Capture(context.Context, Snapshot, ReadRequest) (string, error)
}

Terminal is the adapter every control operation goes through. The local implementation speaks tmux; the remote-host plan supplies the second one.

Every method takes an already-pinned Snapshot rather than a bare Target for the mutating operations, because the adapter re-proves the occupant against that pin immediately before it writes and refuses a replacement.

type TranscriptMessage

type TranscriptMessage struct {
	Role string    `json:"role"`
	Text string    `json:"text"`
	At   time.Time `json:"at,omitzero"`
}

TranscriptMessage is the small stable projection of a provider conversation turn. It is deliberately not the conversation adapter's own Message type: that shape belongs to the history plugin and would make this JSON contract hostage to a UI's needs.

type TranscriptReader

type TranscriptReader interface {
	SessionMessages(ctx context.Context, target Target, limit int) ([]TranscriptMessage, error)
}

TranscriptReader is the injected exact-transcript seam.

It is separate from the terminal adapter on purpose: conversation stores and terminal control are independent, and a missing or disabled Conversations plugin must never disable start, prompt, wait, or a terminal read. M3 adds the binding that supplies an implementation; until then a Service leaves this nil and `--source transcript` answers transcript_unavailable rather than guessing the newest session with the same working directory.

type WaitRequest

type WaitRequest struct {
	Target  Target
	Until   []Status
	Timeout time.Duration
}

Jump to

Keyboard shortcuts

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