protocol

package
v0.7.12 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package protocol defines the text-based IPC protocol for daemon communication.

Index

Constants

View Source
const (
	VerbRun         = "RUN"
	VerbRunJSON     = "RUN-JSON"
	VerbProc        = "PROC"
	VerbProxy       = "PROXY"
	VerbProxyLog    = "PROXYLOG"
	VerbCurrentPage = "CURRENTPAGE"
	VerbTunnel      = "TUNNEL"
	VerbChaos       = "CHAOS"
	VerbDetect      = "DETECT"
	VerbOverlay     = "OVERLAY"
	VerbSession     = "SESSION"
	VerbPing        = "PING"
	VerbInfo        = "INFO"
	VerbShutdown    = "SHUTDOWN"
)

Command verbs

View Source
const (
	SubVerbStatus      = "STATUS"
	SubVerbOutput      = "OUTPUT"
	SubVerbStop        = "STOP"
	SubVerbList        = "LIST"
	SubVerbCleanupPort = "CLEANUP-PORT"
)

Process sub-verbs

View Source
const (
	SubVerbStart = "START"
	SubVerbExec  = "EXEC"
	SubVerbToast = "TOAST"
)

Proxy sub-verbs

View Source
const (
	SubVerbQuery = "QUERY"
	SubVerbClear = "CLEAR"
	SubVerbStats = "STATS"
)

ProxyLog sub-verbs

View Source
const (
	SubVerbSet      = "SET"
	SubVerbActivity = "ACTIVITY"
)

Overlay sub-verbs

View Source
const (
	SubVerbEnable     = "ENABLE"
	SubVerbDisable    = "DISABLE"
	SubVerbAddRule    = "ADD-RULE"
	SubVerbRemoveRule = "REMOVE-RULE"
	SubVerbListRules  = "LIST-RULES"
	SubVerbPreset     = "PRESET"
	SubVerbReset      = "RESET"
)

Chaos sub-verbs

View Source
const (
	SubVerbRegister   = "REGISTER"
	SubVerbUnregister = "UNREGISTER"
	SubVerbHeartbeat  = "HEARTBEAT"
	SubVerbSend       = "SEND"
	SubVerbSchedule   = "SCHEDULE"
	SubVerbCancel     = "CANCEL"
	SubVerbTasks      = "TASKS"
	SubVerbFind       = "FIND" // Find session by directory ancestry
	SubVerbAttach     = "ATTACH"
)

Session sub-verbs

View Source
const (
	// CommandTerminator marks the end of a command (including any data payload)
	CommandTerminator = ";;"

	// DataMarker separates arguments from data length
	DataMarker = "--"
)

Protocol constants for resilient parsing

View Source
const (
	SubVerbGet = "GET"
)

CurrentPage sub-verbs

Variables

View Source
var ErrJSONInsteadOfCommand = errors.New("json_instead_of_command")

ErrJSONInsteadOfCommand indicates JSON was sent instead of a protocol command.

ValidVerbs lists all valid command verbs.

Functions

func FormatChunk

func FormatChunk(data []byte) []byte

FormatChunk formats a streaming chunk with base64 encoding. Format: CHUNK -- LENGTH\nBASE64DATA;;

func FormatCommand

func FormatCommand(cmd *Command) []byte

FormatCommand formats a command for transmission using the resilient format. Format: VERB [SUBVERB] [ARGS...] [-- LENGTH\nBASE64DATA];; Data is base64 encoded to safely handle JavaScript, JSON, and binary content.

func FormatData

func FormatData(data []byte) []byte

FormatData formats a binary data response with base64 encoding. Format: DATA -- LENGTH\nBASE64DATA;;

func FormatEnd

func FormatEnd() []byte

FormatEnd formats an END response for chunked streams. Format: END;;

func FormatErr

func FormatErr(code ErrorCode, message string) []byte

FormatErr formats an error response. Format: ERR code message;;

func FormatJSON

func FormatJSON(data []byte) []byte

FormatJSON formats a JSON response with base64 encoded data. Format: JSON -- LENGTH\nBASE64DATA;;

func FormatOK

func FormatOK(message string) []byte

FormatOK formats a simple OK response. Format: OK [message];;

func FormatPong

func FormatPong() []byte

FormatPong formats a PONG response. Format: PONG;;

func ParseLengthPrefixed

func ParseLengthPrefixed(line string, prefix string) (int, error)

ParseLengthPrefixed parses a length-prefixed response line. Returns the length value and any remaining data on the line.

Types

type ChaosConfigPayload

type ChaosConfigPayload struct {
	Enabled     bool               `json:"enabled"`
	Rules       []*ChaosRuleConfig `json:"rules,omitempty"`
	GlobalOdds  float64            `json:"global_odds,omitempty"`  // 0.0-1.0
	Seed        int64              `json:"seed,omitempty"`         // For reproducible chaos
	LoggingMode int                `json:"logging_mode,omitempty"` // 0=silent, 1=testing, 2=coordinated
}

ChaosConfigPayload represents the full chaos configuration for SET command.

type ChaosRuleConfig

type ChaosRuleConfig struct {
	ID          string   `json:"id"`
	Name        string   `json:"name,omitempty"`
	Type        string   `json:"type"` // latency, out_of_order, slow_drip, disconnect, http_error, truncate, etc.
	Enabled     bool     `json:"enabled"`
	URLPattern  string   `json:"url_pattern,omitempty"`
	Methods     []string `json:"methods,omitempty"`
	Probability float64  `json:"probability,omitempty"` // 0.0-1.0, default 1.0

	// Latency config
	MinLatencyMs int `json:"min_latency_ms,omitempty"`
	MaxLatencyMs int `json:"max_latency_ms,omitempty"`
	JitterMs     int `json:"jitter_ms,omitempty"`

	// Slow-drip config
	BytesPerMs int `json:"bytes_per_ms,omitempty"`
	ChunkSize  int `json:"chunk_size,omitempty"`

	// Connection drop config
	DropAfterPercent float64 `json:"drop_after_percent,omitempty"`
	DropAfterBytes   int64   `json:"drop_after_bytes,omitempty"`

	// Error injection config
	ErrorCodes   []int  `json:"error_codes,omitempty"`
	ErrorMessage string `json:"error_message,omitempty"`

	// Truncation config
	TruncatePercent float64 `json:"truncate_percent,omitempty"`

	// Out-of-order config
	ReorderMinRequests int `json:"reorder_min_requests,omitempty"`
	ReorderMaxWaitMs   int `json:"reorder_max_wait_ms,omitempty"`

	// Stale config
	StaleDelayMs int64 `json:"stale_delay_ms,omitempty"`
}

ChaosRuleConfig represents configuration for a CHAOS ADD-RULE command.

type Command

type Command struct {
	Verb        string   // Primary command verb (RUN, PROC, PROXY, etc.)
	SubVerb     string   // Optional sub-verb (STATUS, OUTPUT, START, etc.)
	Args        []string // Positional arguments
	Data        []byte   // Optional binary/JSON data payload
	SessionCode string   // Session code for scoping (required unless Global flag is set)
}

Command represents a parsed command from the client.

type DirectoryFilter

type DirectoryFilter struct {
	SessionCode string `json:"session_code,omitempty"` // Session code for scoping (preferred)
	Directory   string `json:"directory,omitempty"`    // Current working directory (legacy, use session_code instead)
	Global      bool   `json:"global,omitempty"`       // If true, ignore all filtering
}

DirectoryFilter represents directory scoping for list operations. Priority: Global > SessionCode > Directory

type ErrUnknownCommand

type ErrUnknownCommand struct {
	Verb       string
	ValidVerbs []string
}

ErrUnknownCommand indicates an unknown command verb was sent.

func (*ErrUnknownCommand) Error

func (e *ErrUnknownCommand) Error() string

type ErrorCode

type ErrorCode string

ErrorCode represents daemon error codes.

const (
	ErrNotFound       ErrorCode = "not_found"
	ErrAlreadyExists  ErrorCode = "already_exists"
	ErrInvalidState   ErrorCode = "invalid_state"
	ErrShuttingDown   ErrorCode = "shutting_down"
	ErrPortInUse      ErrorCode = "port_in_use"
	ErrInvalidArgs    ErrorCode = "invalid_args"
	ErrInvalidAction  ErrorCode = "invalid_action"  // Unknown action/sub-verb
	ErrInvalidCommand ErrorCode = "invalid_command" // Unknown command/verb
	ErrMissingParam   ErrorCode = "missing_param"   // Required parameter missing
	ErrTimeout        ErrorCode = "timeout"
	ErrInternal       ErrorCode = "internal"
)

type LogQueryFilter

type LogQueryFilter struct {
	Types       []string `json:"types,omitempty"`
	Methods     []string `json:"methods,omitempty"`
	URLPattern  string   `json:"url_pattern,omitempty"`
	StatusCodes []int    `json:"status_codes,omitempty"`
	Since       string   `json:"since,omitempty"`
	Until       string   `json:"until,omitempty"`
	Limit       int      `json:"limit,omitempty"`
}

LogQueryFilter represents filters for PROXYLOG QUERY command.

type OutputFilter

type OutputFilter struct {
	Stream string `json:"stream,omitempty"` // stdout, stderr, combined
	Tail   int    `json:"tail,omitempty"`
	Head   int    `json:"head,omitempty"`
	Grep   string `json:"grep,omitempty"`
	GrepV  bool   `json:"grep_v,omitempty"`
}

OutputFilter represents filters for PROC OUTPUT command.

type Parser

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

Parser handles parsing of protocol commands and responses. Commands use explicit terminators for resilience:

  • Commands end with ";;"
  • Data is indicated by "--" followed by length

Format:

VERB [SUBVERB] [ARGS...] [-- LENGTH\nDATA];;

Examples:

PING;;
PROC STATUS my-process;;
PROXY START dev http://localhost:3000 8080;;
PROXY START dev http://localhost:3000 8080 -- 12\n{"path":"."};;

func NewParser

func NewParser(r io.Reader) *Parser

NewParser creates a new protocol parser.

func (*Parser) ParseCommand

func (p *Parser) ParseCommand() (*Command, error)

ParseCommand reads and parses a command from the reader. It reads until it finds the command terminator ";;".

func (*Parser) ParseResponse

func (p *Parser) ParseResponse() (*Response, error)

ParseResponse reads and parses a response from the reader. Responses also use the ";;" terminator and "--" data marker.

func (*Parser) Resync

func (p *Parser) Resync() error

Resync attempts to resynchronize the parser by scanning for the next terminator. This can be used to recover from parse errors.

type ProxyStartConfig

type ProxyStartConfig struct {
	ID          string        `json:"id"`
	TargetURL   string        `json:"target_url"`
	Port        int           `json:"port"`
	MaxLogSize  int           `json:"max_log_size,omitempty"`
	BindAddress string        `json:"bind_address,omitempty"` // "127.0.0.1" (default) or "0.0.0.0" (all interfaces)
	PublicURL   string        `json:"public_url,omitempty"`   // Public URL for tunnels (e.g., "https://abc.trycloudflare.com")
	Tunnel      *TunnelConfig `json:"tunnel,omitempty"`
}

ProxyStartConfig represents configuration for a PROXY START command.

type Response

type Response struct {
	Type    ResponseType
	Message string // For OK/ERR responses
	Code    string // Error code for ERR responses
	Data    []byte // Binary/JSON data for DATA/JSON/CHUNK responses
}

Response represents a response from the daemon.

type ResponseType

type ResponseType string

ResponseType indicates the type of response.

const (
	ResponseOK    ResponseType = "OK"
	ResponseErr   ResponseType = "ERR"
	ResponseData  ResponseType = "DATA"
	ResponseJSON  ResponseType = "JSON"
	ResponseChunk ResponseType = "CHUNK"
	ResponseEnd   ResponseType = "END"
	ResponsePong  ResponseType = "PONG"
)

type RunConfig

type RunConfig struct {
	ID         string   `json:"id"`
	Path       string   `json:"path"`
	Mode       string   `json:"mode"` // background, foreground, foreground-raw
	ScriptName string   `json:"script_name,omitempty"`
	Raw        bool     `json:"raw,omitempty"`
	Command    string   `json:"command,omitempty"`
	Args       []string `json:"args,omitempty"`
	Env        []string `json:"env,omitempty"` // Environment variables from client (KEY=VALUE format)
}

RunConfig represents configuration for a RUN command.

type SessionRegisterConfig added in v0.7.0

type SessionRegisterConfig struct {
	OverlayPath string   `json:"overlay_path"`   // Unix socket path for overlay
	ProjectPath string   `json:"project_path"`   // Directory where session was started
	Command     string   `json:"command"`        // Command being run (e.g., "claude")
	Args        []string `json:"args,omitempty"` // Command arguments
}

SessionRegisterConfig represents configuration for a SESSION REGISTER command.

type SessionScheduleConfig added in v0.7.0

type SessionScheduleConfig struct {
	SessionCode string `json:"session_code"` // Target session
	Duration    string `json:"duration"`     // Go duration string (e.g., "5m", "1h30m")
	Message     string `json:"message"`      // Message to deliver
	ProjectPath string `json:"project_path"` // For project-scoped storage
}

SessionScheduleConfig represents configuration for a SESSION SCHEDULE command.

type StructuredError

type StructuredError struct {
	Code         ErrorCode `json:"code"`
	Message      string    `json:"message"`
	Command      string    `json:"command,omitempty"`       // The command that was called
	Action       string    `json:"action,omitempty"`        // The action that was attempted
	ValidActions []string  `json:"valid_actions,omitempty"` // List of valid actions
	Param        string    `json:"param,omitempty"`         // The parameter that was invalid/missing
	ValidParams  []string  `json:"valid_params,omitempty"`  // List of valid parameter values
}

StructuredError contains programmatic error details for MCP translation.

type ToastConfig

type ToastConfig struct {
	Type     string `json:"type"`               // success, error, warning, info
	Title    string `json:"title,omitempty"`    // Toast title (optional)
	Message  string `json:"message"`            // Toast message
	Duration int    `json:"duration,omitempty"` // Duration in ms (0 for default)
}

ToastConfig represents configuration for a PROXY TOAST command.

type TunnelConfig

type TunnelConfig struct {
	// Provider is the tunnel provider: "ngrok", "cloudflared", "tailscale", or "custom"
	Provider string `json:"provider"`
	// Command is used when Provider is "custom" - the full command to run
	Command string `json:"command,omitempty"`
	// Args are additional arguments for the tunnel command
	Args []string `json:"args,omitempty"`
	// AuthToken is the authentication token (for ngrok)
	AuthToken string `json:"auth_token,omitempty"`
	// Region is the tunnel region (optional)
	Region string `json:"region,omitempty"`
}

TunnelConfig represents configuration for starting a tunnel alongside a proxy.

type TunnelStartConfig

type TunnelStartConfig struct {
	ID         string `json:"id"`                    // Tunnel ID (usually same as proxy ID)
	Provider   string `json:"provider"`              // "cloudflare" or "ngrok"
	LocalPort  int    `json:"local_port"`            // Local port to tunnel
	LocalHost  string `json:"local_host,omitempty"`  // Local host (default: localhost)
	BinaryPath string `json:"binary_path,omitempty"` // Optional path to tunnel binary
	ProxyID    string `json:"proxy_id,omitempty"`    // Optional proxy ID to auto-configure public_url
}

TunnelStartConfig represents configuration for a TUNNEL START command.

type Writer

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

Writer provides methods for writing protocol messages.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a new protocol writer.

func (*Writer) WriteChunk

func (w *Writer) WriteChunk(data []byte) error

WriteChunk writes a chunk in a streaming response.

func (*Writer) WriteCommand

func (w *Writer) WriteCommand(verb string, args []string, data []byte) error

WriteCommand writes a command.

func (*Writer) WriteCommandWithData

func (w *Writer) WriteCommandWithData(verb string, args []string, subVerb *string, data []byte) error

WriteCommandWithData writes a command with optional data payload.

func (*Writer) WriteCommandWithSubVerb

func (w *Writer) WriteCommandWithSubVerb(verb, subVerb string, args []string, data []byte) error

WriteCommandWithSubVerb writes a command with a sub-verb.

func (*Writer) WriteData

func (w *Writer) WriteData(data []byte) error

WriteData writes a binary data response.

func (*Writer) WriteEnd

func (w *Writer) WriteEnd() error

WriteEnd writes the END marker for chunked responses.

func (*Writer) WriteErr

func (w *Writer) WriteErr(code ErrorCode, message string) error

WriteErr writes an error response.

func (*Writer) WriteJSON

func (w *Writer) WriteJSON(data []byte) error

WriteJSON writes a JSON response.

func (*Writer) WriteOK

func (w *Writer) WriteOK(message string) error

WriteOK writes an OK response.

func (*Writer) WritePong

func (w *Writer) WritePong() error

WritePong writes a PONG response.

Jump to

Keyboard shortcuts

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