rpcclient

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 17 Imported by: 2

Documentation

Overview

Package rpcclient is a Go client for `pig --mode rpc`: it spawns the agent in RPC mode and provides a typed API for all operations.

Upstream reference:

.upstream/current/packages/coding-agent/src/modes/rpc/rpc-client.ts

Upstream's Promise-returning methods are blocking calls here. Responses and events arrive on one stdout reader goroutine; event listeners run on it in registration order, as they run on Node's event loop upstream.

Index

Constants

View Source
const (
	DefaultTimeout = 60 * time.Second
)

Upstream's fixed waits: the start settle delay, the per-request response timeout, the SIGTERM grace period in stop, and the default wait/collect timeout.

Variables

This section is empty.

Functions

func ReadJSONLLines

func ReadJSONLLines(r io.Reader, onLine func([]byte) bool) error

ReadJSONLLines reads strict JSONL records from r. It splits only on LF, removes one trailing CR, delivers blank records, and delivers a final unterminated record. Returning false from onLine stops the read.

Types

type AgentMessage

type AgentMessage struct {
	Role string          `json:"role"`
	Raw  json.RawMessage `json:"-"`
}

AgentMessage is one agent message; Role is decoded and Raw keeps the complete message.

func (*AgentMessage) UnmarshalJSON

func (m *AgentMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the role and retains the raw message.

type BashResult

type BashResult struct {
	Output         string `json:"output"`
	ExitCode       *int   `json:"exitCode,omitempty"`
	Cancelled      bool   `json:"cancelled"`
	Truncated      bool   `json:"truncated"`
	FullOutputPath string `json:"fullOutputPath,omitempty"`
}

BashResult mirrors upstream BashResult. ExitCode is nil when the command was killed or cancelled.

type CancelledResult

type CancelledResult struct {
	Cancelled bool `json:"cancelled"`
}

CancelledResult mirrors the {cancelled} result of session replacement.

type ClearQueueResult

type ClearQueueResult struct {
	Steering []string `json:"steering"`
	FollowUp []string `json:"followUp"`
}

ClearQueueResult mirrors upstream clearQueue's result.

type CompactionResult

type CompactionResult struct {
	Summary              string          `json:"summary"`
	FirstKeptEntryID     string          `json:"firstKeptEntryId"`
	TokensBefore         int             `json:"tokensBefore"`
	EstimatedTokensAfter *int            `json:"estimatedTokensAfter,omitempty"`
	Usage                json.RawMessage `json:"usage,omitempty"`
	Details              json.RawMessage `json:"details,omitempty"`
}

CompactionResult mirrors upstream CompactionResult; Usage and Details stay raw JSON.

type ContextUsage

type ContextUsage struct {
	Tokens        *int     `json:"tokens"`
	ContextWindow int      `json:"contextWindow"`
	Percent       *float64 `json:"percent"`
}

ContextUsage mirrors upstream ContextUsage.

type CycleModelResult

type CycleModelResult struct {
	Model         ModelReference `json:"model"`
	ThinkingLevel ThinkingLevel  `json:"thinkingLevel"`
	IsScoped      bool           `json:"isScoped"`
}

CycleModelResult mirrors upstream cycleModel's non-null result.

type CycleThinkingLevelResult

type CycleThinkingLevelResult struct {
	Level ThinkingLevel `json:"level"`
}

CycleThinkingLevelResult mirrors upstream cycleThinkingLevel's non-null result.

type ExportHtmlResult

type ExportHtmlResult struct {
	Path string `json:"path"`
}

ExportHtmlResult mirrors upstream exportHtml's result.

type ForkMessage

type ForkMessage struct {
	EntryID string `json:"entryId"`
	Text    string `json:"text"`
}

ForkMessage mirrors one getForkMessages entry.

type ForkResult

type ForkResult struct {
	Text      string `json:"text"`
	Cancelled bool   `json:"cancelled"`
}

ForkResult mirrors upstream fork's result.

type GetEntriesResult

type GetEntriesResult struct {
	Entries []SessionEntry `json:"entries"`
	LeafID  *string        `json:"leafId"`
}

GetEntriesResult mirrors upstream getEntries' result.

type GetTreeResult

type GetTreeResult struct {
	Tree   []SessionTreeNode `json:"tree"`
	LeafID *string           `json:"leafId"`
}

GetTreeResult mirrors upstream getTree's result.

type ImageContent

type ImageContent struct {
	Data     string `json:"data"`
	MimeType string `json:"mimeType"`
}

ImageContent is a pi-ai image block; it marshals with type "image".

func (ImageContent) MarshalJSON

func (c ImageContent) MarshalJSON() ([]byte, error)

MarshalJSON emits the pi-ai wire shape {type:"image", data, mimeType}.

type JsonAgentSessionEvent

type JsonAgentSessionEvent struct {
	Type string
	Raw  json.RawMessage `json:"-"`
}

JsonAgentSessionEvent is one stdout record that is not a response to a pending request: an agent session event, an extension UI request, or an unmatched response. Type is its "type" field; Raw is the complete record.

type Model

type Model struct {
	ID            string          `json:"id"`
	Name          string          `json:"name"`
	API           string          `json:"api"`
	Provider      string          `json:"provider"`
	BaseURL       string          `json:"baseUrl"`
	Reasoning     bool            `json:"reasoning"`
	Input         []string        `json:"input"`
	ContextWindow int             `json:"contextWindow"`
	MaxTokens     int             `json:"maxTokens"`
	Raw           json.RawMessage `json:"-"`
}

Model is the model object RPC responses carry (pi-ai Model). The common fields are decoded; Raw keeps the complete object.

func (*Model) UnmarshalJSON

func (m *Model) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the common fields and retains the raw object.

type ModelInfo

type ModelInfo struct {
	Provider      string `json:"provider"`
	ID            string `json:"id"`
	ContextWindow int    `json:"contextWindow"`
	Reasoning     bool   `json:"reasoning"`
}

ModelInfo mirrors upstream ModelInfo.

type ModelReference

type ModelReference struct {
	Provider string `json:"provider"`
	ID       string `json:"id"`
}

ModelReference is the {provider, id} pair upstream setModel and cycleModel declare.

type RpcClient

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

RpcClient mirrors upstream RpcClient.

func NewRpcClient

func NewRpcClient(options RpcClientOptions) *RpcClient

NewRpcClient mirrors the upstream constructor.

func (*RpcClient) Abort

func (c *RpcClient) Abort() error

Abort aborts the current operation.

func (*RpcClient) AbortBash

func (c *RpcClient) AbortBash() error

AbortBash aborts the running bash command.

func (*RpcClient) AbortRetry

func (c *RpcClient) AbortRetry() error

AbortRetry aborts an in-progress retry.

func (*RpcClient) Bash

func (c *RpcClient) Bash(cmd string) (BashResult, error)

Bash executes a bash command.

func (*RpcClient) ClearQueue

func (c *RpcClient) ClearQueue() (ClearQueueResult, error)

ClearQueue clears queued steering and follow-up messages, returning their text.

func (*RpcClient) Clone

func (c *RpcClient) Clone() (CancelledResult, error)

Clone clones the current active branch into a new session.

func (*RpcClient) CollectEvents

func (c *RpcClient) CollectEvents(timeout time.Duration) ([]JsonAgentSessionEvent, error)

CollectEvents collects events up to and including the next agent_settled event (upstream default timeout: DefaultTimeout).

func (*RpcClient) Compact

func (c *RpcClient) Compact(customInstructions *string) (CompactionResult, error)

Compact compacts the session context.

func (*RpcClient) CycleModel

func (c *RpcClient) CycleModel() (*CycleModelResult, error)

CycleModel cycles to the next model; nil means there was nothing to cycle.

func (*RpcClient) CycleThinkingLevel

func (c *RpcClient) CycleThinkingLevel() (*CycleThinkingLevelResult, error)

CycleThinkingLevel cycles the thinking level; nil means the model has only one level.

func (*RpcClient) ExportHtml

func (c *RpcClient) ExportHtml(outputPath *string) (ExportHtmlResult, error)

ExportHtml exports the session to HTML.

func (*RpcClient) FollowUp

func (c *RpcClient) FollowUp(message string, images []ImageContent) error

FollowUp queues a follow-up message for after the agent finishes.

func (*RpcClient) Fork

func (c *RpcClient) Fork(entryID string) (ForkResult, error)

Fork forks from a specific message.

func (*RpcClient) GetAvailableModels

func (c *RpcClient) GetAvailableModels() ([]ModelInfo, error)

GetAvailableModels lists the available models.

func (*RpcClient) GetAvailableThinkingLevels

func (c *RpcClient) GetAvailableThinkingLevels() ([]ThinkingLevel, error)

GetAvailableThinkingLevels lists the current model's thinking levels.

func (*RpcClient) GetCommands

func (c *RpcClient) GetCommands() ([]RpcSlashCommand, error)

GetCommands lists extension commands, prompt templates, and skills.

func (*RpcClient) GetEntries

func (c *RpcClient) GetEntries(since *string) (GetEntriesResult, error)

GetEntries returns session entries in append order, optionally only those after the since entry id.

func (*RpcClient) GetForkMessages

func (c *RpcClient) GetForkMessages() ([]ForkMessage, error)

GetForkMessages lists the messages available for forking.

func (*RpcClient) GetLastAssistantText

func (c *RpcClient) GetLastAssistantText() (*string, error)

GetLastAssistantText returns the last assistant message text, or nil.

func (*RpcClient) GetMessages

func (c *RpcClient) GetMessages() ([]AgentMessage, error)

GetMessages returns all messages in the session.

func (*RpcClient) GetSessionStats

func (c *RpcClient) GetSessionStats() (SessionStats, error)

GetSessionStats returns session statistics.

func (*RpcClient) GetState

func (c *RpcClient) GetState() (RpcSessionState, error)

GetState returns the current session state.

func (*RpcClient) GetStderr

func (c *RpcClient) GetStderr() string

GetStderr returns the collected stderr output.

func (*RpcClient) GetTree

func (c *RpcClient) GetTree() (GetTreeResult, error)

GetTree returns the session entry tree.

func (*RpcClient) NewSession

func (c *RpcClient) NewSession(parentSession *string) (CancelledResult, error)

NewSession starts a new session, optionally tracking parentSession. The result reports whether an extension cancelled it.

func (*RpcClient) OnEvent

func (c *RpcClient) OnEvent(listener RpcEventListener) func()

OnEvent mirrors upstream onEvent and returns the unsubscribe function.

func (*RpcClient) Prompt

func (c *RpcClient) Prompt(message string, images []ImageContent) error

Prompt sends a prompt and returns once it is accepted; use OnEvent for the streamed events and WaitForIdle for completion.

func (*RpcClient) PromptAndWait

func (c *RpcClient) PromptAndWait(message string, images []ImageContent, timeout time.Duration) ([]JsonAgentSessionEvent, error)

PromptAndWait sends a prompt and returns every event through agent_settled. Collection starts before the prompt is sent, as upstream's does.

func (*RpcClient) SetAutoCompaction

func (c *RpcClient) SetAutoCompaction(enabled bool) error

SetAutoCompaction enables or disables auto-compaction.

func (*RpcClient) SetAutoRetry

func (c *RpcClient) SetAutoRetry(enabled bool) error

SetAutoRetry enables or disables auto-retry.

func (*RpcClient) SetFollowUpMode

func (c *RpcClient) SetFollowUpMode(mode string) error

SetFollowUpMode sets the follow-up mode ("all" or "one-at-a-time").

func (*RpcClient) SetModel

func (c *RpcClient) SetModel(provider, modelID string) (ModelReference, error)

SetModel sets the model by provider and id.

func (*RpcClient) SetSessionName

func (c *RpcClient) SetSessionName(name string) error

SetSessionName sets the session display name.

func (*RpcClient) SetSteeringMode

func (c *RpcClient) SetSteeringMode(mode string) error

SetSteeringMode sets the steering mode ("all" or "one-at-a-time").

func (*RpcClient) SetThinkingLevel

func (c *RpcClient) SetThinkingLevel(level ThinkingLevel) error

SetThinkingLevel sets the thinking level.

func (*RpcClient) Start

func (c *RpcClient) Start() error

Start spawns the agent in RPC mode, waits upstream's 100ms settle delay, and reports an exit that happened during it.

func (*RpcClient) Steer

func (c *RpcClient) Steer(message string, images []ImageContent) error

Steer queues a steering message to interrupt the agent mid-run.

func (*RpcClient) Stop

func (c *RpcClient) Stop()

Stop mirrors upstream stop: it detaches stdout callbacks, sends SIGTERM, waits up to one second before killing, reaps the child and closes owned pipes. It is safe in an event callback; use Wait outside callbacks to join readers.

func (*RpcClient) SwitchSession

func (c *RpcClient) SwitchSession(sessionPath string) (CancelledResult, error)

SwitchSession switches to another session file; the result reports whether an extension cancelled it.

func (*RpcClient) Wait

func (c *RpcClient) Wait()

Wait joins all owned stream readers and writers after Stop. Call it outside event callbacks and before starting another lifecycle; Stop alone is reentrant.

func (*RpcClient) WaitForIdle

func (c *RpcClient) WaitForIdle(timeout time.Duration) error

WaitForIdle waits for the next agent_settled event (upstream default timeout: DefaultTimeout).

type RpcClientOptions

type RpcClientOptions struct {
	// CliPath is the agent executable. Default: "pig".
	CliPath string
	// Cwd is the working directory for the agent.
	Cwd string
	// Env adds or overrides environment variables on top of the current
	// process environment.
	Env map[string]string
	// Provider is passed as --provider when non-empty.
	Provider string
	// Model is passed as --model when non-empty.
	Model string
	// Args are appended after the mode, provider, and model arguments.
	Args []string
}

RpcClientOptions mirrors upstream RpcClientOptions. CliPath names the pig executable to run (upstream runs `node <cliPath>`); it defaults to "pig", resolved through PATH.

type RpcEventListener

type RpcEventListener func(event JsonAgentSessionEvent)

RpcEventListener mirrors upstream RpcEventListener.

type RpcResponse

type RpcResponse struct {
	ID      string          `json:"id,omitempty"`
	Type    string          `json:"type"`
	Command string          `json:"command"`
	Success bool            `json:"success"`
	Data    json.RawMessage `json:"data,omitempty"`
	Error   string          `json:"error,omitempty"`
}

RpcResponse mirrors upstream RpcResponse. Data holds the raw success payload; Error holds the failure message.

type RpcSessionState

type RpcSessionState struct {
	Model                 *Model        `json:"model,omitempty"`
	ThinkingLevel         ThinkingLevel `json:"thinkingLevel"`
	IsStreaming           bool          `json:"isStreaming"`
	IsCompacting          bool          `json:"isCompacting"`
	SteeringMode          string        `json:"steeringMode"`
	FollowUpMode          string        `json:"followUpMode"`
	SessionFile           *string       `json:"sessionFile,omitempty"`
	SessionID             string        `json:"sessionId"`
	SessionName           *string       `json:"sessionName,omitempty"`
	AutoCompactionEnabled bool          `json:"autoCompactionEnabled"`
	MessageCount          int           `json:"messageCount"`
	PendingMessageCount   int           `json:"pendingMessageCount"`
}

RpcSessionState mirrors upstream RpcSessionState.

type RpcSlashCommand

type RpcSlashCommand struct {
	Name        string        `json:"name"`
	Description string        `json:"description,omitempty"`
	Source      string        `json:"source"`
	SourceInfo  RpcSourceInfo `json:"sourceInfo"`
}

RpcSlashCommand mirrors upstream RpcSlashCommand.

type RpcSourceInfo

type RpcSourceInfo struct {
	Path    string `json:"path"`
	Source  string `json:"source"`
	Scope   string `json:"scope"`
	Origin  string `json:"origin"`
	BaseDir string `json:"baseDir,omitempty"`
}

RpcSourceInfo mirrors the sourceInfo carried by RpcSlashCommand.

type SessionEntry

type SessionEntry struct {
	Type      string          `json:"type"`
	ID        string          `json:"id"`
	ParentID  *string         `json:"parentId"`
	Timestamp string          `json:"timestamp"`
	Raw       json.RawMessage `json:"-"`
}

SessionEntry is one session entry. The identity fields are decoded; Raw keeps the complete entry.

func (*SessionEntry) UnmarshalJSON

func (e *SessionEntry) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the identity fields and retains the raw entry.

type SessionStats

type SessionStats struct {
	SessionFile       *string            `json:"sessionFile,omitempty"`
	SessionID         string             `json:"sessionId"`
	UserMessages      int                `json:"userMessages"`
	AssistantMessages int                `json:"assistantMessages"`
	ToolCalls         int                `json:"toolCalls"`
	ToolResults       int                `json:"toolResults"`
	TotalMessages     int                `json:"totalMessages"`
	Tokens            SessionStatsTokens `json:"tokens"`
	Cost              float64            `json:"cost"`
	ContextUsage      *ContextUsage      `json:"contextUsage,omitempty"`
}

SessionStats mirrors upstream SessionStats.

type SessionStatsTokens

type SessionStatsTokens struct {
	Input      int `json:"input"`
	Output     int `json:"output"`
	CacheRead  int `json:"cacheRead"`
	CacheWrite int `json:"cacheWrite"`
	Total      int `json:"total"`
}

SessionStatsTokens mirrors SessionStats.tokens.

type SessionTreeNode

type SessionTreeNode struct {
	Entry          SessionEntry      `json:"entry"`
	Children       []SessionTreeNode `json:"children"`
	Label          *string           `json:"label,omitempty"`
	LabelTimestamp *string           `json:"labelTimestamp,omitempty"`
}

SessionTreeNode mirrors upstream SessionTreeNode.

type ThinkingLevel

type ThinkingLevel string

ThinkingLevel is a pi-agent-core thinking level ("off", "minimal", "low", "medium", "high", "xhigh", "max").

Jump to

Keyboard shortcuts

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