Documentation
¶
Overview ¶
Package rpc corresponds to pi's packages/coding-agent/src/modes/rpc.
pi: modes/rpc/jsonl.ts — strict LF-only JSONL framing for the RPC protocol.
Go adaptation (declared): pi attaches data/end listeners to a Node stream and swaps a StringDecoder for incremental UTF-8 handling. Go reads from an io.Reader in a goroutine; bufio.Reader already handles incomplete runes at chunk boundaries, so the StringDecoder equivalent collapses into the reader. Framing is otherwise identical: split on LF only, tolerate a trailing CR, and emit a final unterminated line at EOF.
pi: modes/rpc/rpc-mode.ts — RPC mode (headless operation with a JSON stdin/stdout protocol). Used for embedding the agent in other programs: commands arrive as JSON lines on stdin, responses and session events are emitted as JSON lines on stdout.
Protocol:
- Commands: JSON objects with a `type` field, optional `id` for correlation.
- Responses: { type: "response", command, success, data?/error? }.
- Events: AgentSessionEvent objects streamed as they occur.
Extension UI: pi emits extension_ui_request and expects extension_ui_response round-trips. pig does not port the extension system (Phase 7 not done, and pig extensions are incompatible with pi's), so no request is ever emitted; incoming extension_ui_response lines are recognized and ignored. The get_commands "extension" source is likewise always empty.
Go adaptation (declared): pi's runRpcMode is a never-resolving promise and writes through module-global output-guard/jsonl functions (mocked in tests). pig splits the entry into RunRpcMode (takes over stdout, uses os.Stdin) and an unexported runRpcMode that receives an rpcIO so tests can inject a writer and a reader. Each input line is handled in its own goroutine so steer/abort commands can run while a prompt is streaming (pi: `void handleInputLine`, whose async handlers run concurrently).
pi: modes/rpc/rpc-types.ts — RPC protocol types for headless operation.
Commands are sent as JSON lines on stdin; responses and events are emitted as JSON lines on stdout. The wire shape (camelCase keys, string literals) is a hard constraint (AGENTS.md 线格式): command `type` values, response `command` values, and field names must match pi exactly.
Go adaptation (declared): pi models RpcCommand/RpcResponse as discriminated unions. Go collapses each union into one struct carrying every variant's members plus a `Type` (and, for responses, `Command`) discriminator — the same treatment as AgentSessionEvent. Inbound decoding ignores members that do not belong to the active variant; outbound responses are built by the success/error helpers in rpc_mode.go so only the active variant's keys marshal (via omitempty).
Index ¶
- func AttachJsonlLineReader(reader io.Reader, onLine func(line string)) (detach func(), done <-chan struct{})
- func RunRpcMode(ctx context.Context, host RpcRuntimeHost) int
- func SerializeJsonLine(value any) (string, error)
- type RpcCommand
- type RpcExtensionUIRequest
- type RpcExtensionUIResponse
- type RpcResponse
- type RpcRuntimeHost
- type RpcSessionState
- type RpcSlashCommand
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AttachJsonlLineReader ¶
func AttachJsonlLineReader(reader io.Reader, onLine func(line string)) (detach func(), done <-chan struct{})
AttachJsonlLineReader attaches an LF-only JSONL reader to a stream (pi: attachJsonlLineReader). It intentionally does not use Go's text/scanner or any Unicode-separator-aware splitter: records split on `\n` only, because U+2028/U+2029 are valid inside JSON strings.
The returned detach stops the reader loop after the current read returns; the underlying reader is not closed (matching pi, which only removes its stream listeners). The done channel closes when the loop exits.
func RunRpcMode ¶
func RunRpcMode(ctx context.Context, host RpcRuntimeHost) int
RunRpcMode runs in RPC mode (pi: runRpcMode). It takes over stdout and blocks until stdin reaches EOF or a termination signal arrives. Returns the process exit code.
func SerializeJsonLine ¶
SerializeJsonLine serializes a single strict JSONL record (pi: serializeJsonLine). Framing is LF-only; payload strings may contain other Unicode separators such as U+2028 and U+2029. Clients must split records on `\n` only.
Go's encoding/json unconditionally escapes U+2028/U+2029 (to keep output valid JavaScript) and, when escaping HTML, `<`, `>`, `&`; pi's JSON.stringify does neither. The encoder runs with SetEscapeHTML(false) and then unescapes only the two line-separator escapes, matching JSON.stringify.
Types ¶
type RpcCommand ¶
type RpcCommand struct {
ID string `json:"id,omitempty"`
Type string `json:"type"`
// Prompting
Message string `json:"message,omitempty"`
Images []types.ImageContent `json:"images,omitempty"`
StreamingBehavior string `json:"streamingBehavior,omitempty"`
// new_session
ParentSession string `json:"parentSession,omitempty"`
// set_model
Provider string `json:"provider,omitempty"`
ModelID string `json:"modelId,omitempty"`
// set_thinking_level
Level types.ModelThinkingLevel `json:"level,omitempty"`
// set_steering_mode / set_follow_up_mode
Mode string `json:"mode,omitempty"`
// compact
CustomInstructions string `json:"customInstructions,omitempty"`
// set_auto_compaction / set_auto_retry
Enabled *bool `json:"enabled,omitempty"`
// bash
Command string `json:"command,omitempty"`
ExcludeFromContext *bool `json:"excludeFromContext,omitempty"`
// export_html
OutputPath string `json:"outputPath,omitempty"`
// switch_session
SessionPath string `json:"sessionPath,omitempty"`
// fork
EntryID string `json:"entryId,omitempty"`
// get_entries
Since string `json:"since,omitempty"`
// set_session_name
Name string `json:"name,omitempty"`
}
RpcCommand is a command received on stdin (pi: RpcCommand union). All variant members are optional except Type.
type RpcExtensionUIRequest ¶
type RpcExtensionUIRequest struct {
Type string `json:"type"`
ID string `json:"id"`
Method string `json:"method"`
}
RpcExtensionUIRequest is a request to the host for user input (pi: RpcExtensionUIRequest). Never emitted by pig.
type RpcExtensionUIResponse ¶
type RpcExtensionUIResponse struct {
Type string `json:"type"`
ID string `json:"id"`
Value string `json:"value,omitempty"`
Confirmed bool `json:"confirmed,omitempty"`
Cancelled bool `json:"cancelled,omitempty"`
}
RpcExtensionUIResponse is the host's answer (pi: RpcExtensionUIResponse). Recognized on stdin and discarded.
type RpcResponse ¶
type RpcResponse struct {
ID string `json:"id,omitempty"`
Type string `json:"type"`
Command string `json:"command"`
Success bool `json:"success"`
// Data is the variant payload; nil = key omitted. A null payload (pi's
// `data: null`) is carried as json.RawMessage("null") so the key is
// emitted.
Data any `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
RpcResponse is a response emitted on stdout (pi: RpcResponse union). The success/error helpers populate ID/Type/Command/Success plus either Data or Error.
type RpcRuntimeHost ¶
type RpcRuntimeHost interface {
Session() *core.AgentSession
NewSession(ctx context.Context, options *core.RuntimeNewSessionOptions) (cancelled bool, err error)
Fork(ctx context.Context, entryID string, options *core.ForkOptions) (*core.ForkResult, error)
SwitchSession(ctx context.Context, sessionPath string, options *core.SwitchSessionOptions) (cancelled bool, err error)
Dispose() error
SetRebindSession(rebindSession func(session *core.AgentSession) error)
}
RpcRuntimeHost is the runtime host consumption surface (pi: AgentSessionRuntime's members used by runRpcMode). Mirrors modes.PrintRuntimeHost.
type RpcSessionState ¶
type RpcSessionState struct {
// Model is the current model; nil = omitted (pi: model?).
Model *types.Model `json:"model,omitempty"`
// ThinkingLevel is the current reasoning level.
ThinkingLevel types.ModelThinkingLevel `json:"thinkingLevel"`
// IsStreaming mirrors session.isStreaming.
IsStreaming bool `json:"isStreaming"`
// IsCompacting mirrors session.isCompacting.
IsCompacting bool `json:"isCompacting"`
// SteeringMode is "all" | "one-at-a-time".
SteeringMode string `json:"steeringMode"`
// FollowUpMode is "all" | "one-at-a-time".
FollowUpMode string `json:"followUpMode"`
// SessionFile is the session file path; "" = omitted (pi: sessionFile?).
SessionFile string `json:"sessionFile,omitempty"`
// SessionID is the session identifier.
SessionID string `json:"sessionId"`
// SessionName is the display name; "" = omitted (pi: sessionName?).
SessionName string `json:"sessionName,omitempty"`
// AutoCompactionEnabled reports whether auto-compaction is on.
AutoCompactionEnabled bool `json:"autoCompactionEnabled"`
// MessageCount is the transcript length.
MessageCount int `json:"messageCount"`
// PendingMessageCount is the number of queued messages.
PendingMessageCount int `json:"pendingMessageCount"`
}
RpcSessionState is the get_state response payload (pi: RpcSessionState).
type RpcSlashCommand ¶
type RpcSlashCommand struct {
// Name is the command name (without a leading slash).
Name string `json:"name"`
// Description is the human-readable description; "" = omitted.
Description string `json:"description,omitempty"`
// Source is "extension" | "prompt" | "skill".
Source string `json:"source"`
// SourceInfo is the source metadata for the owning resource.
SourceInfo utils.SourceInfo `json:"sourceInfo"`
}
RpcSlashCommand is a command available for invocation via prompt (pi: RpcSlashCommand).