Documentation
¶
Overview ¶
Package protocol defines the text-based IPC protocol for daemon communication.
Index ¶
- Constants
- Variables
- func FormatChunk(data []byte) []byte
- func FormatCommand(cmd *Command) []byte
- func FormatData(data []byte) []byte
- func FormatEnd() []byte
- func FormatErr(code ErrorCode, message string) []byte
- func FormatJSON(data []byte) []byte
- func FormatOK(message string) []byte
- func FormatPong() []byte
- func ParseLengthPrefixed(line string, prefix string) (int, error)
- type ChaosConfigPayload
- type ChaosRuleConfig
- type Command
- type DirectoryFilter
- type ErrUnknownCommand
- type ErrorCode
- type LogQueryFilter
- type OutputFilter
- type Parser
- type ProxyStartConfig
- type Response
- type ResponseType
- type RunConfig
- type SessionRegisterConfig
- type SessionScheduleConfig
- type StructuredError
- type ToastConfig
- type TunnelConfig
- type TunnelStartConfig
- type Writer
- func (w *Writer) WriteChunk(data []byte) error
- func (w *Writer) WriteCommand(verb string, args []string, data []byte) error
- func (w *Writer) WriteCommandWithData(verb string, args []string, subVerb *string, data []byte) error
- func (w *Writer) WriteCommandWithSubVerb(verb, subVerb string, args []string, data []byte) error
- func (w *Writer) WriteData(data []byte) error
- func (w *Writer) WriteEnd() error
- func (w *Writer) WriteErr(code ErrorCode, message string) error
- func (w *Writer) WriteJSON(data []byte) error
- func (w *Writer) WriteOK(message string) error
- func (w *Writer) WritePong() error
Constants ¶
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
const ( SubVerbStatus = "STATUS" SubVerbOutput = "OUTPUT" SubVerbStop = "STOP" SubVerbList = "LIST" SubVerbCleanupPort = "CLEANUP-PORT" )
Process sub-verbs
const ( SubVerbStart = "START" SubVerbExec = "EXEC" SubVerbToast = "TOAST" )
Proxy sub-verbs
const ( SubVerbQuery = "QUERY" SubVerbClear = "CLEAR" SubVerbStats = "STATS" )
ProxyLog sub-verbs
const ( SubVerbSet = "SET" SubVerbActivity = "ACTIVITY" )
Overlay sub-verbs
const ( SubVerbEnable = "ENABLE" SubVerbDisable = "DISABLE" SubVerbAddRule = "ADD-RULE" SubVerbRemoveRule = "REMOVE-RULE" SubVerbListRules = "LIST-RULES" SubVerbPreset = "PRESET" SubVerbReset = "RESET" )
Chaos sub-verbs
const ( SubVerbRegister = "REGISTER" SubVerbUnregister = "UNREGISTER" SubVerbHeartbeat = "HEARTBEAT" SubVerbSend = "SEND" SubVerbSchedule = "SCHEDULE" SubVerbCancel = "CANCEL" SubVerbTasks = "TASKS" )
Session sub-verbs
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
const (
SubVerbGet = "GET"
)
CurrentPage sub-verbs
Variables ¶
var ErrJSONInsteadOfCommand = errors.New("json_instead_of_command")
ErrJSONInsteadOfCommand indicates JSON was sent instead of a protocol command.
var ValidVerbs = []string{ VerbRun, VerbRunJSON, VerbProc, VerbProxy, VerbProxyLog, VerbCurrentPage, VerbTunnel, VerbChaos, VerbDetect, VerbOverlay, VerbSession, VerbPing, VerbInfo, VerbShutdown, }
ValidVerbs lists all valid command verbs.
Functions ¶
func FormatChunk ¶
FormatChunk formats a streaming chunk with base64 encoding. Format: CHUNK -- LENGTH\nBASE64DATA;;
func FormatCommand ¶
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 ¶
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 FormatJSON ¶
FormatJSON formats a JSON response with base64 encoded data. Format: JSON -- LENGTH\nBASE64DATA;;
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
}
Command represents a parsed command from the client.
type DirectoryFilter ¶
type DirectoryFilter struct {
Directory string `json:"directory,omitempty"` // Current working directory (defaults to "." if empty)
Global bool `json:"global,omitempty"` // If true, ignore directory filtering
}
DirectoryFilter represents directory scoping for list operations.
type ErrUnknownCommand ¶
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 (*Parser) ParseCommand ¶
ParseCommand reads and parses a command from the reader. It reads until it finds the command terminator ";;".
func (*Parser) ParseResponse ¶
ParseResponse reads and parses a response from the reader. Responses also use the ";;" terminator and "--" data marker.
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 (*Writer) WriteChunk ¶
WriteChunk writes a chunk in a streaming response.
func (*Writer) WriteCommand ¶
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 ¶
WriteCommandWithSubVerb writes a command with a sub-verb.