Documentation
¶
Overview ¶
Ports packages/coding-agent/src/modes/rpc/jsonl.ts
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
- func AppendJsonLine(dst []byte, value any) ([]byte, error)
- func ReadJSONLBatches(r io.Reader, onBatch func([][]byte) bool) error
- func ReadJSONLLines(r io.Reader, onLine func([]byte) bool) error
- func SerializeJsonLine(value any) ([]byte, error)
- type AgentMessage
- type BashResult
- type CancelledResult
- type ClearQueueResult
- type CompactionResult
- type ContextUsage
- type CycleModelResult
- type CycleThinkingLevelResult
- type ExportHtmlResult
- type ForkMessage
- type ForkResult
- type GetEntriesResult
- type GetTreeResult
- type ImageContent
- type JsonAgentSessionEvent
- type Model
- type ModelInfo
- type ModelReference
- type PromptDisposition
- type QueuedInputDisposition
- type RpcClient
- func (c *RpcClient) Abort() error
- func (c *RpcClient) AbortBash() error
- func (c *RpcClient) AbortRetry() error
- func (c *RpcClient) Bash(cmd string) (BashResult, error)
- func (c *RpcClient) ClearQueue() (ClearQueueResult, error)
- func (c *RpcClient) Clone() (CancelledResult, error)
- func (c *RpcClient) CollectEvents(timeout time.Duration) ([]JsonAgentSessionEvent, error)
- func (c *RpcClient) Compact(customInstructions *string) (CompactionResult, error)
- func (c *RpcClient) CycleModel() (*CycleModelResult, error)
- func (c *RpcClient) CycleThinkingLevel() (*CycleThinkingLevelResult, error)
- func (c *RpcClient) ExportHtml(outputPath *string) (ExportHtmlResult, error)
- func (c *RpcClient) FollowUp(message string, images []ImageContent) (QueuedInputDisposition, error)
- func (c *RpcClient) Fork(entryID string) (ForkResult, error)
- func (c *RpcClient) GetAvailableModels() ([]ModelInfo, error)
- func (c *RpcClient) GetAvailableThinkingLevels() ([]ThinkingLevel, error)
- func (c *RpcClient) GetCommands() ([]RpcSlashCommand, error)
- func (c *RpcClient) GetEntries(since *string) (GetEntriesResult, error)
- func (c *RpcClient) GetExtensions() ([]string, error)
- func (c *RpcClient) GetForkMessages() ([]ForkMessage, error)
- func (c *RpcClient) GetLastAssistantText() (*string, error)
- func (c *RpcClient) GetMessages() ([]AgentMessage, error)
- func (c *RpcClient) GetSessionStats() (SessionStats, error)
- func (c *RpcClient) GetState() (RpcSessionState, error)
- func (c *RpcClient) GetStderr() string
- func (c *RpcClient) GetTree() (GetTreeResult, error)
- func (c *RpcClient) NewSession(parentSession *string) (CancelledResult, error)
- func (c *RpcClient) OnEvent(listener RpcEventListener) func()
- func (c *RpcClient) Prompt(message string, images []ImageContent, streamingBehavior *StreamingBehavior) (PromptDisposition, error)
- func (c *RpcClient) PromptAndWait(message string, images []ImageContent, timeout time.Duration) ([]JsonAgentSessionEvent, error)
- func (c *RpcClient) SetAutoCompaction(enabled bool) error
- func (c *RpcClient) SetAutoRetry(enabled bool) error
- func (c *RpcClient) SetFollowUpMode(mode string) error
- func (c *RpcClient) SetModel(provider, modelID string) (ModelReference, error)
- func (c *RpcClient) SetSessionName(name string) error
- func (c *RpcClient) SetSteeringMode(mode string) error
- func (c *RpcClient) SetThinkingLevel(level ThinkingLevel) error
- func (c *RpcClient) Start() error
- func (c *RpcClient) Steer(message string, images []ImageContent) (QueuedInputDisposition, error)
- func (c *RpcClient) Stop()
- func (c *RpcClient) SwitchSession(sessionPath string) (CancelledResult, error)
- func (c *RpcClient) Wait()
- func (c *RpcClient) WaitForIdle(timeout time.Duration) error
- type RpcClientOptions
- type RpcEventListener
- type RpcResponse
- type RpcSessionState
- type RpcSlashCommand
- type RpcSourceInfo
- type SessionEntry
- type SessionStats
- type SessionStatsTokens
- type SessionTreeNode
- type StreamingBehavior
- type ThinkingLevel
Constants ¶
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 AppendJsonLine ¶
AppendJsonLine appends SerializeJsonLine(value) to dst, encoding into dst itself. On an error it returns dst with its original length.
func ReadJSONLBatches ¶
ReadJSONLBatches preserves the complete records already available in one buffered read. A caller can admit that input callback's commands before running their awaited continuations, as attachJsonlLineReader does in Node's onData callback. Partial and final unterminated records retain ReadJSONLLines framing.
func ReadJSONLLines ¶
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.
func SerializeJsonLine ¶
SerializeJsonLine is JSON.stringify(value) followed by the LF that frames a record (jsonl.ts serializeJsonLine).
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 ¶
ForkMessage mirrors one getForkMessages entry.
type ForkResult ¶
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 ¶
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 ¶
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 ¶
ModelReference is the {provider, id} pair upstream setModel and cycleModel declare.
type PromptDisposition ¶
type PromptDisposition string
PromptDisposition is what `prompt` did with its input: an extension command or input handler consumed it ("handled"), it was queued behind a running turn ("queued"), or a run started ("started").
upstream: .upstream/v0.99.1/packages/coding-agent/src/core/agent-session.ts:290 (PromptDisposition)
const ( PromptDispositionHandled PromptDisposition = "handled" PromptDispositionQueued PromptDisposition = "queued" PromptDispositionStarted PromptDisposition = "started" )
The dispositions of upstream's PromptDisposition union.
type QueuedInputDisposition ¶
type QueuedInputDisposition string
QueuedInputDisposition is what `steer` and `follow_up` did with their input: an input handler consumed it ("handled") or it was queued ("queued").
upstream: .upstream/v0.99.1/packages/coding-agent/src/core/agent-session.ts:289 (QueuedInputDisposition)
const ( QueuedInputDispositionHandled QueuedInputDisposition = "handled" QueuedInputDispositionQueued QueuedInputDisposition = "queued" )
The dispositions of upstream's QueuedInputDisposition union.
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) AbortRetry ¶
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) (QueuedInputDisposition, error)
FollowUp queues a follow-up message for after the agent finishes and returns its disposition.
upstream: .upstream/v0.99.1/packages/coding-agent/src/modes/rpc/rpc-client.ts:218-221 (followUp)
func (*RpcClient) Fork ¶
func (c *RpcClient) Fork(entryID string) (ForkResult, error)
Fork forks from a specific message.
func (*RpcClient) GetAvailableModels ¶
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) GetExtensions ¶
GetExtensions lists the resolved paths of the loaded extensions in load order.
func (*RpcClient) GetForkMessages ¶
func (c *RpcClient) GetForkMessages() ([]ForkMessage, error)
GetForkMessages lists the messages available for forking.
func (*RpcClient) GetLastAssistantText ¶
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) 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, streamingBehavior *StreamingBehavior) (PromptDisposition, error)
Prompt sends a prompt and returns its disposition once it is accepted; use OnEvent for the streamed events. If the disposition is "handled", no run started for this prompt, so do not wait for agent_settled. streamingBehavior is nil unless the prompt may arrive during a run.
upstream: .upstream/v0.99.1/packages/coding-agent/src/modes/rpc/rpc-client.ts:198-205 (prompt)
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 ¶
SetAutoCompaction enables or disables auto-compaction.
func (*RpcClient) SetAutoRetry ¶
SetAutoRetry enables or disables auto-retry.
func (*RpcClient) SetFollowUpMode ¶
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 ¶
SetSessionName sets the session display name.
func (*RpcClient) SetSteeringMode ¶
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 ¶
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) (QueuedInputDisposition, error)
Steer queues a steering message to interrupt the agent mid-run and returns its disposition.
upstream: .upstream/v0.99.1/packages/coding-agent/src/modes/rpc/rpc-client.ts:210-213 (steer)
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.
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 StreamingBehavior ¶
type StreamingBehavior string
StreamingBehavior says how a prompt sent during a run is queued: "steer" or "followUp".
const ( StreamingBehaviorSteer StreamingBehavior = "steer" StreamingBehaviorFollowUp StreamingBehavior = "followUp" )
The values of upstream's `streamingBehavior?: "steer" | "followUp"`.
type ThinkingLevel ¶
type ThinkingLevel string
ThinkingLevel is a pi-agent-core thinking level ("off", "minimal", "low", "medium", "high", "xhigh", "max").