wire

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 12 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 wire is the message envelope and codec shared by every stagent connection: app ↔ bridge (over the SSH exec channel) and the local IPC links (holder, daemon, hook, bridge). One JSON object per line.

Index

Constants

View Source
const (
	ErrBadRequest     = "bad_request"
	ErrUnknownMethod  = "unknown_method"
	ErrNotFound       = "not_found"
	ErrUnsupported    = "unsupported"
	ErrInternal       = "internal"
	ErrUnavailable    = "unavailable"
	ErrVersion        = "version_mismatch"
	ErrSessionEnded   = "session_ended"
	ErrNotSizeOwner   = "not_size_owner"
	ErrApprovalClosed = "approval_closed"
)

Stable error codes.

View Source
const (
	MethodHello = "hello"
	MethodPing  = "ping"

	// Served by the holder (bridge forwards to Layout.HolderAddr(id)).
	MethodSessionAttach     = "session.attach"
	MethodSessionDetach     = "session.detach"
	MethodSessionInput      = "session.input"
	MethodSessionResize     = "session.resize"
	MethodSessionScrollback = "session.scrollback"
	MethodSessionSignal     = "session.signal"
	MethodSessionInfo       = "session.info"

	// Served by the bridge itself (spawns a detached holder).
	MethodSessionSpawn = "session.spawn"

	// Served by the daemon.
	MethodWatch                 = "watch"
	MethodSessionsList          = "sessions.list"
	MethodConversationsList     = "conversations.list"
	MethodTranscriptGet         = "transcript.get"
	MethodTranscriptSubscribe   = "transcript.subscribe"
	MethodTranscriptUnsubscribe = "transcript.unsubscribe"
	MethodApprovalsList         = "approvals.list"
	MethodApprovalRespond       = "approval.respond"
	MethodConfigGet             = "config.get"
	MethodConfigSet             = "config.set"
	MethodNotifyTest            = "notify.test"

	// Notifications (server → app).
	NotifyEvent          = "event"           // Event
	NotifySessionUpdated = "session.updated" // Session
	NotifySessionRemoved = "session.removed" // SessionRef
	NotifyOutput         = "output"          // OutputParams
	NotifyResize         = "resize"          // ResizeParams
	NotifyClosed         = "closed"          // ClosedParams
	NotifyTranscript     = "transcript"      // TranscriptParams
)
View Source
const (
	CapScreenMode = "screen_mode" // session.attach mode "screen"
	CapSpawn      = "spawn"
	CapHooks      = "hooks" // approvals / hook-derived state
	CapTranscript = "transcript"
	CapPush       = "push" // ntfy / webhook
)

Capabilities advertised in HelloResult.

View Source
const (
	AttachRaw    = "raw"    // PTY bytes as produced, resynced by snapshot on overflow
	AttachScreen = "screen" // ANSI diffs of changed rows, at most FPS per second
)

Attach modes.

View Source
const (
	SignalInterrupt = "interrupt" // Ctrl-C to the PTY
	SignalTerminate = "terminate" // SIGTERM / CTRL_BREAK / TerminateProcess after grace
	SignalKill      = "kill"      // SIGKILL / TerminateProcess
)

Signals for session.signal.

View Source
const (
	// holder → daemon (persistent connection opened by the holder)
	MethodHolderRegister = "holder.register" // Session → HolderRegisterResult
	MethodHolderUpdate   = "holder.update"   // notification, SessionPatch
	MethodHolderNotify   = "holder.notify"   // notification, HolderNotifyParams
	MethodHolderEnded    = "holder.ended"    // notification, ClosedParams

	// hook → daemon (one request per connection)
	MethodHookEvent = "hook.event" // HookEventParams → HookEventResult

	// install / doctor → daemon
	MethodDaemonStatus   = "daemon.status"   // → DaemonStatus
	MethodDaemonShutdown = "daemon.shutdown" // → {}
	// daemon → holder notification sent before a deliberate shutdown
	// (daemon.shutdown, SIGTERM): holders keep retrying but stop
	// auto-starting the daemon, so `uninstall --level stop` sticks.
	MethodDaemonStopping = "daemon.stopping"
)
View Source
const (
	StateWorking       = "working"
	StateIdle          = "idle"
	StateWaitingInput  = "waiting_input"
	StateNeedsApproval = "needs_approval"
	StateExited        = "exited"
)

Session states.

View Source
const (
	SourceHook     = "hook"     // harness hook (structured)
	SourceTerminal = "terminal" // OSC 9/99/777 notification, BEL
	SourceActivity = "activity" // output activity / quiescence
	SourceProcess  = "process"  // child process exit
)

Where a state came from, highest priority first.

View Source
const (
	HarnessClaude = "claude"
	HarnessCodex  = "codex"
	HarnessOmp    = "omp"
	HarnessOther  = "other"
)

Harness ids.

View Source
const (
	ModePassthrough = "passthrough" // runs in a local terminal; that terminal owns the size
	ModeDetached    = "detached"    // no local terminal; the app owns the size
)

Session modes.

View Source
const (
	EventSessionStarted    = "session_started"
	EventSessionEnded      = "session_ended"
	EventStateChanged      = "state_changed"
	EventNotification      = "notification"
	EventApprovalRequested = "approval_requested"
	EventApprovalResolved  = "approval_resolved"
)

Event kinds.

View Source
const (
	LevelInfo = "info"
	LevelWarn = "warn"
)

Notification levels.

View Source
const (
	DecisionAllow = "allow"
	DecisionDeny  = "deny"
	DecisionNone  = "none" // no decision: the harness asks in the terminal
)

Approval decisions.

View Source
const EnvSessionID = "STAGENT_SESSION_ID"

EnvSessionID is exported to the agent process so hooks can name the PTY session they belong to.

View Source
const MaxLine = 16 << 20

MaxLine bounds a single message. Output chunks are capped well below this by their producers; anything larger is a protocol violation.

Variables

DaemonMethods are forwarded by the bridge to the daemon.

View Source
var ErrTooLong = errors.New("wire: message exceeds MaxLine")

ErrTooLong is returned by Read for a line over MaxLine.

HolderMethods are forwarded by the bridge to the session's holder.

View Source
var KeySequences = map[string]string{
	"enter": "\r", "esc": "\x1b", "tab": "\t", "shift-tab": "\x1b[Z",
	"backspace": "\x7f", "delete": "\x1b[3~", "space": " ",
	"up": "\x1b[A", "down": "\x1b[B", "right": "\x1b[C", "left": "\x1b[D",
	"home": "\x1b[H", "end": "\x1b[F", "pageup": "\x1b[5~", "pagedown": "\x1b[6~",
	"ctrl-c": "\x03", "ctrl-d": "\x04", "ctrl-z": "\x1a", "ctrl-l": "\x0c",
	"ctrl-r": "\x12", "ctrl-u": "\x15", "ctrl-o": "\x0f", "ctrl-t": "\x14",
}

KeySequences maps session.input key names to the bytes sent to the PTY.

Functions

func DetectHarness

func DetectHarness(argv []string) string

DetectHarness maps a command's executable to a harness id.

func NewSessionID

func NewSessionID() string

NewSessionID returns a random 16-hex-char id (paths.sessionIDLen).

Types

type Approval

type Approval struct {
	RequestID string `json:"request_id"`
	SessionID string `json:"session_id,omitempty"`
	Harness   string `json:"harness"`
	ToolName  string `json:"tool_name,omitempty"`
	Summary   string `json:"summary"` // human readable, e.g. the command line
	CreatedAt int64  `json:"created_at"`
	ExpiresAt int64  `json:"expires_at"`
}

Approval is a pending permission request raised by a blocking hook.

type ApprovalResolvedData

type ApprovalResolvedData struct {
	RequestID string `json:"request_id"`
	Decision  string `json:"decision"`
	By        string `json:"by"` // "app" | "timeout" | "cancelled"
}

ApprovalResolvedData is Event.Data for approval_resolved.

type ApprovalRespondParams

type ApprovalRespondParams struct {
	RequestID string `json:"request_id"`
	Decision  string `json:"decision"` // allow | deny
	Message   string `json:"message,omitempty"`
}

type ApprovalsListResult

type ApprovalsListResult struct {
	Approvals []Approval `json:"approvals"`
}

type AttachParams

type AttachParams struct {
	ID   string `json:"id"`
	Mode string `json:"mode"`          // default raw
	FPS  int    `json:"fps,omitempty"` // screen mode cap, default 15, max 30
}

type AttachResult

type AttachResult struct {
	Cols int    `json:"cols"`
	Rows int    `json:"rows"`
	Mode string `json:"mode"`
}

type ClosedParams

type ClosedParams struct {
	ID       string `json:"id"`
	ExitCode int    `json:"exit_code"`
}

type Codec

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

Codec reads and writes newline-delimited JSON messages. Write is safe for concurrent use; Read must be called from one goroutine.

func NewCodec

func NewCodec(r io.Reader, w io.Writer) *Codec

NewCodec wraps a reader and writer (often the same net.Conn).

func (*Codec) Encode

func (c *Codec) Encode(v any) error

Encode writes v as one JSON line. The output is pure ASCII (non-ASCII runes are \u-escaped) so shells or consoles that re-encode stdout — PowerShell on Windows — cannot corrupt it.

func (*Codec) Notify

func (c *Codec) Notify(method string, params any) error

Notify sends a notification.

func (*Codec) Read

func (c *Codec) Read() (*Msg, error)

Read decodes the next message. Blank lines are skipped. A trailing '\r' is tolerated so CRLF-translating transports still work.

func (*Codec) ReadLine

func (c *Codec) ReadLine() ([]byte, error)

ReadLine returns the next non-blank line without its line ending, for line protocols whose objects are not Msg envelopes (`stagent follow`). Blank lines are skipped and a trailing '\r' is removed, as for Read.

func (*Codec) Reply

func (c *Codec) Reply(id *int64, result any) error

Reply answers request id with result (nil → {}).

func (*Codec) ReplyError

func (c *Codec) ReplyError(id *int64, e *Error) error

ReplyError answers request id with an error.

func (*Codec) Request

func (c *Codec) Request(id int64, method string, params any) error

Request sends a request with the given id.

func (*Codec) Write

func (c *Codec) Write(m *Msg) error

Write encodes m as one line.

type Config

type Config struct {
	Notify    NotifyConfig    `json:"notify"`
	Retention RetentionConfig `json:"retention"`
	// ApprovalTimeoutSec bounds how long a blocking hook waits for the app.
	ApprovalTimeoutSec int `json:"approval_timeout_sec"`
	// IdleAfterMs: quiet time after which output activity counts as idle.
	IdleAfterMs int `json:"idle_after_ms"`
}

Config is the daemon configuration. Zero values mean "default".

func (Config) WithDefaults

func (c Config) WithDefaults() Config

WithDefaults fills zero fields with the documented defaults.

type ConfigResult

type ConfigResult struct {
	Config Config `json:"config"`
}

type ConfigSetParams

type ConfigSetParams struct {
	Config Config `json:"config"`
}

type Conversation

type Conversation struct {
	Harness       string `json:"harness"`
	ID            string `json:"id"`
	Cwd           string `json:"cwd"`
	Title         string `json:"title"`
	UpdatedAt     int64  `json:"updated_at"` // unix ms (file mtime)
	Path          string `json:"path"`
	LiveSessionID string `json:"live_session_id,omitempty"`
}

Conversation is one stored conversation of a harness (conversations.list).

type ConversationsListParams

type ConversationsListParams struct {
	Harness []string `json:"harness,omitempty"` // empty = all
	Limit   int      `json:"limit,omitempty"`   // default 50 per harness
}

type ConversationsListResult

type ConversationsListResult struct {
	Conversations []Conversation `json:"conversations"`
}

type DaemonStatus

type DaemonStatus struct {
	PID       int    `json:"pid"`
	Version   string `json:"version"`
	StartedAt int64  `json:"started_at"`
	Sessions  int    `json:"sessions"`
	Bridges   int    `json:"bridges"`
}

type Error

type Error struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Error is a protocol-level failure. Code is a stable machine-readable string (see the Err* constants); Message is for humans.

func Errorf

func Errorf(code, format string, args ...any) *Error

Errorf builds an *Error.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Seq       int64           `json:"seq"`
	Time      int64           `json:"time"` // unix ms
	SessionID string          `json:"session_id,omitempty"`
	Kind      string          `json:"kind"`
	Data      json.RawMessage `json:"data,omitempty"`
}

Event is one entry of the daemon's event log.

type HelloParams

type HelloParams struct {
	Protocol int    `json:"protocol"`
	Client   string `json:"client"` // e.g. "ssh-term/2.38.0"
}

type HelloResult

type HelloResult struct {
	Protocol     int      `json:"protocol"`
	Version      string   `json:"version"`
	OS           string   `json:"os"`   // linux | darwin | windows
	Arch         string   `json:"arch"` // amd64 | arm64
	Home         string   `json:"home"`
	Capabilities []string `json:"capabilities"`
}

type HolderNotifyParams

type HolderNotifyParams struct {
	ID    string `json:"id"`
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
	Bell  bool   `json:"bell,omitempty"`
}

HolderNotifyParams is a notification the program itself emitted (OSC 9 / 99 / 777, or BEL).

type HolderRegisterResult

type HolderRegisterResult struct {
	IdleAfterMs int `json:"idle_after_ms"`
}

type HookEventParams

type HookEventParams struct {
	Harness   string          `json:"harness"`
	Event     string          `json:"event"`                // harness-native event name
	SessionID string          `json:"session_id,omitempty"` // $STAGENT_SESSION_ID
	Payload   json.RawMessage `json:"payload,omitempty"`    // hook stdin (or notify argv JSON)
}

type HookEventResult

type HookEventResult struct {
	Decision string `json:"decision,omitempty"` // allow | deny | none (permission events)
	Message  string `json:"message,omitempty"`
}

type InputParams

type InputParams struct {
	ID     string   `json:"id"`
	Text   string   `json:"text,omitempty"`
	Paste  string   `json:"paste,omitempty"`
	Keys   []string `json:"keys,omitempty"` // names from KeySequences
	Submit bool     `json:"submit,omitempty"`
}

InputParams is applied in order: Text (raw), Paste (bracketed when the program enabled bracketed paste), Keys, then a CR if Submit.

type Message

type Message struct {
	Role     string `json:"role"` // user | assistant | tool | system
	Text     string `json:"text"`
	ToolName string `json:"tool_name,omitempty"`
	Time     int64  `json:"time,omitempty"` // unix ms
}

Message is one normalized conversation entry.

type Msg

type Msg struct {
	ID     *int64          `json:"id,omitempty"`
	Method string          `json:"method,omitempty"`
	Params json.RawMessage `json:"params,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  *Error          `json:"error,omitempty"`
}

Msg is the envelope. Requests carry ID+Method(+Params), responses ID and Result or Error, notifications Method(+Params) without ID.

func (*Msg) IsRequest

func (m *Msg) IsRequest() bool

IsRequest reports whether m expects a response.

func (*Msg) IsResponse

func (m *Msg) IsResponse() bool

IsResponse reports whether m answers an earlier request.

type NotificationData

type NotificationData struct {
	Title string `json:"title"`
	Body  string `json:"body"`
	Level string `json:"level"`
	// Reason: "waiting_input" | "needs_approval" | "turn_complete" |
	// "exited" | "terminal" (OSC/BEL from the program) | "test" | "digest".
	Reason string `json:"reason"`
	// Count > 1 for a digest folding several notifications together.
	Count int `json:"count,omitempty"`
}

NotificationData is Event.Data for notification — what the app shows and what offline push channels send. Body never contains terminal output.

type NotifyConfig

type NotifyConfig struct {
	Ntfy    NtfyConfig    `json:"ntfy"`
	Webhook WebhookConfig `json:"webhook"`
	// DebounceMs: minimum stable time of a state before it notifies.
	DebounceMs int `json:"debounce_ms"`
	// DigestWindowMs: notifications within this window fold into one digest.
	DigestWindowMs int `json:"digest_window_ms"`
}

NotifyConfig configures offline push channels.

type NtfyConfig

type NtfyConfig struct {
	Enabled bool   `json:"enabled"`
	Server  string `json:"server"` // default https://ntfy.sh
	Topic   string `json:"topic"`
	Token   string `json:"token,omitempty"`
}

NtfyConfig is an ntfy.sh (or self-hosted ntfy) topic.

type OutputParams

type OutputParams struct {
	ID    string `json:"id"`
	Data  []byte `json:"data"` // base64 in JSON
	Reset bool   `json:"reset,omitempty"`
}

OutputParams carries terminal bytes to an attached client. When Reset is true the client must clear its terminal (screen + scrollback) and then write Data, which is a full ANSI snapshot of the current screen.

type ResizeParams

type ResizeParams struct {
	ID   string `json:"id"`
	Cols int    `json:"cols"`
	Rows int    `json:"rows"`
	// Force lets the app take the size of a passthrough session.
	Force bool `json:"force,omitempty"`
}

type RetentionConfig

type RetentionConfig struct {
	EventsDays         int `json:"events_days"`
	EventsMax          int `json:"events_max"`
	ScrollbackDays     int `json:"scrollback_days"`
	ScrollbackTotalMiB int `json:"scrollback_total_mib"`
	// ScrollbackSessionMiB caps one session (segments of 1 MiB).
	ScrollbackSessionMiB int `json:"scrollback_session_mib"`
}

RetentionConfig bounds on-disk data.

type ScrollbackParams

type ScrollbackParams struct {
	ID string `json:"id"`
	// Before is an exclusive byte offset into the session's output stream;
	// 0 means "up to the latest byte".
	Before   int64 `json:"before,omitempty"`
	MaxBytes int   `json:"max_bytes,omitempty"` // default 256 KiB, max 1 MiB
}

type ScrollbackResult

type ScrollbackResult struct {
	Data  []byte `json:"data"`  // raw PTY bytes [Start, End)
	Start int64  `json:"start"` // stream offset of Data[0]
	End   int64  `json:"end"`
	// First is the oldest offset still retained; Start == First means the
	// client has reached the beginning.
	First int64 `json:"first"`
}

type Session

type Session struct {
	ID             string   `json:"id"`
	Harness        string   `json:"harness"`
	Command        []string `json:"command"`
	Cwd            string   `json:"cwd"`
	PID            int      `json:"pid"` // child (agent) pid
	HolderPID      int      `json:"holder_pid"`
	Mode           string   `json:"mode"`
	State          string   `json:"state"`
	StateSource    string   `json:"state_source"`
	Title          string   `json:"title,omitempty"` // OSC 0/2 window title
	ConversationID string   `json:"conversation_id,omitempty"`
	TranscriptPath string   `json:"transcript_path,omitempty"`
	LastMessage    string   `json:"last_message,omitempty"` // short, single line
	Cols           int      `json:"cols"`
	Rows           int      `json:"rows"`
	StartedAt      int64    `json:"started_at"`       // unix ms
	LastActivityAt int64    `json:"last_activity_at"` // unix ms, last PTY output
	ExitCode       *int     `json:"exit_code,omitempty"`
}

Session is one PTY session held by a `stagent run` process.

type SessionEndedData

type SessionEndedData struct {
	ExitCode int `json:"exit_code"`
}

SessionEndedData is Event.Data for session_ended.

type SessionPatch

type SessionPatch struct {
	ID             string  `json:"id"`
	State          *string `json:"state,omitempty"`
	StateSource    *string `json:"state_source,omitempty"`
	Title          *string `json:"title,omitempty"`
	LastActivityAt *int64  `json:"last_activity_at,omitempty"`
	Cols           *int    `json:"cols,omitempty"`
	Rows           *int    `json:"rows,omitempty"`
}

SessionPatch updates a registered session; nil fields are unchanged.

type SessionRef

type SessionRef struct {
	ID string `json:"id"`
}

SessionRef names a session.

type SessionStartedData

type SessionStartedData struct {
	Harness string   `json:"harness"`
	Command []string `json:"command"`
	Cwd     string   `json:"cwd"`
	Mode    string   `json:"mode"`
}

SessionStartedData is Event.Data for session_started.

type SessionsListResult

type SessionsListResult struct {
	Sessions []Session `json:"sessions"`
}

type SignalParams

type SignalParams struct {
	ID     string `json:"id"`
	Signal string `json:"signal"`
}

type SpawnParams

type SpawnParams struct {
	Command []string          `json:"command"`
	Cwd     string            `json:"cwd,omitempty"` // default home
	Cols    int               `json:"cols"`
	Rows    int               `json:"rows"`
	Env     map[string]string `json:"env,omitempty"`
}

type SpawnResult

type SpawnResult struct {
	Session Session `json:"session"`
}

type StateChangedData

type StateChangedData struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Source string `json:"source"`
}

StateChangedData is Event.Data for state_changed.

type TranscriptGetParams

type TranscriptGetParams struct {
	SessionID      string `json:"session_id,omitempty"`
	Harness        string `json:"harness,omitempty"`
	ConversationID string `json:"conversation_id,omitempty"`
	Path           string `json:"path,omitempty"`
	Limit          int    `json:"limit,omitempty"` // default 50
	// Before is the cursor returned by a previous call (byte offset); 0 =
	// newest messages.
	Before int64 `json:"before,omitempty"`
}

TranscriptParams selects a transcript by live session, by conversation, or by path (in that order of precedence).

type TranscriptGetResult

type TranscriptGetResult struct {
	Path     string    `json:"path"`
	Harness  string    `json:"harness"`
	Messages []Message `json:"messages"` // oldest first
	// Cursor to pass as Before for older messages; 0 = beginning reached.
	Cursor int64 `json:"cursor"`
}

type TranscriptParams

type TranscriptParams struct {
	SessionID string    `json:"session_id,omitempty"`
	Path      string    `json:"path"`
	Messages  []Message `json:"messages"`
}

TranscriptParams is the "transcript" notification: new messages appended.

type TranscriptSubscribeParams

type TranscriptSubscribeParams struct {
	SessionID string `json:"session_id,omitempty"`
	Path      string `json:"path,omitempty"`
}

type WatchParams

type WatchParams struct {
	// Since is the last event seq the client has seen; events after it are
	// returned in Missed. 0 replays nothing.
	Since int64 `json:"since"`
}

type WatchResult

type WatchResult struct {
	Sessions  []Session  `json:"sessions"`
	Approvals []Approval `json:"approvals"`
	Seq       int64      `json:"seq"` // latest seq at subscription time
	Missed    []Event    `json:"missed"`
	// Truncated: events between Since and Missed[0] were dropped by retention.
	Truncated bool `json:"truncated"`
}

type WebhookConfig

type WebhookConfig struct {
	Enabled bool              `json:"enabled"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

WebhookConfig posts NotificationData JSON to a URL.

Jump to

Keyboard shortcuts

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