Documentation
¶
Overview ¶
Package pi controls a Pi coding-agent v1.6.0 subprocess through its JSONL RPC protocol.
Index ¶
- Variables
- type BashResult
- type ClearedQueue
- type Command
- type CommandError
- type CompactionResult
- type ContextUsage
- type DispatchError
- type Entries
- type Entry
- type Event
- type ForkMessage
- type HistoryEntry
- type HistoryScope
- type HistoryWindow
- type Image
- type ModelSelection
- type Options
- type PromptResult
- type QueueMode
- type Session
- func (s *Session) Abort(ctx context.Context) error
- func (s *Session) AbortBash(ctx context.Context) error
- func (s *Session) AbortRetry(ctx context.Context) error
- func (s *Session) AvailableModels(ctx context.Context) ([]json.RawMessage, error)
- func (s *Session) AvailableThinkingLevels(ctx context.Context) ([]string, error)
- func (s *Session) Bash(ctx context.Context, command string, excludeFromContext *bool) (BashResult, error)
- func (s *Session) ClearQueue(ctx context.Context) (ClearedQueue, error)
- func (s *Session) Close() error
- func (s *Session) CloseAndDiscard() error
- func (s *Session) Commands(ctx context.Context) ([]Command, error)
- func (s *Session) Compact(ctx context.Context, customInstructions string) (CompactionResult, error)
- func (s *Session) CycleModel(ctx context.Context) (*ModelSelection, error)
- func (s *Session) CycleThinkingLevel(ctx context.Context) (*string, error)
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Entries(ctx context.Context, since string) (Entries, error)
- func (s *Session) Err() error
- func (s *Session) ExportHTML(ctx context.Context, outputPath string) (string, error)
- func (s *Session) FollowUp(ctx context.Context, message string, images []Image) (PromptResult, error)
- func (s *Session) ForkMessages(ctx context.Context) ([]ForkMessage, error)
- func (s *Session) ID() string
- func (s *Session) LastAssistantText(ctx context.Context) (*string, error)
- func (s *Session) Messages(ctx context.Context) ([]json.RawMessage, error)
- func (s *Session) Prompt(ctx context.Context, message string, images []Image, streamingBehavior string) (PromptResult, error)
- func (s *Session) Receive(ctx context.Context) (Event, error)
- func (s *Session) RespondUI(ctx context.Context, response UIResponse) error
- func (s *Session) SetAutoCompaction(ctx context.Context, enabled bool) error
- func (s *Session) SetAutoRetry(ctx context.Context, enabled bool) error
- func (s *Session) SetFollowUpMode(ctx context.Context, mode QueueMode) error
- func (s *Session) SetModel(ctx context.Context, provider, id string) error
- func (s *Session) SetSessionName(ctx context.Context, name string) error
- func (s *Session) SetSteeringMode(ctx context.Context, mode QueueMode) error
- func (s *Session) SetThinkingLevel(ctx context.Context, level string) error
- func (s *Session) State(ctx context.Context) (State, error)
- func (s *Session) Stats(ctx context.Context) (SessionStats, error)
- func (s *Session) Steer(ctx context.Context, message string, images []Image) (PromptResult, error)
- func (s *Session) Tree(ctx context.Context) (Tree, error)
- type SessionHistory
- type SessionInfo
- type SessionStats
- type State
- type TokenUsage
- type Tree
- type TreeNode
- type UIRequest
- type UIResponse
Constants ¶
This section is empty.
Variables ¶
var ErrAmbiguousSession = errors.New("pi: ambiguous saved session ID")
ErrAmbiguousSession indicates that more than one saved file in scope has the same native session ID.
var ErrInvalidHistory = errors.New("pi: invalid saved session history")
ErrInvalidHistory indicates corruption in the selected saved session.
Functions ¶
This section is empty.
Types ¶
type BashResult ¶
type BashResult struct {
Output string `json:"output"`
ExitCode *int `json:"exitCode,omitempty"` // Pi may omit this when the process is killed.
Canceled bool `json:"cancelled"` //nolint:misspell // Pi wire field.
Truncated bool `json:"truncated"`
FullOutputPath *string `json:"fullOutputPath,omitempty"` // Path on the Pi host when Pi saves the full output.
}
BashResult is Pi's final result for a user shell command.
type ClearedQueue ¶
ClearedQueue contains the messages Pi removed, in their original order within each queue.
type Command ¶
type Command struct {
Name string `json:"name"`
Description string `json:"description"`
Source string `json:"source"`
SourceInfo json.RawMessage `json:"sourceInfo"`
}
Command identifies a slash command visible to the current Pi session.
type CommandError ¶
type CommandError struct {
Command string
Message string
Raw json.RawMessage
}
CommandError is an explicit failure response from Pi.
func (*CommandError) Error ¶
func (e *CommandError) Error() string
type CompactionResult ¶
type CompactionResult struct {
Summary string
FirstKeptEntryID string
TokensBefore int64
EstimatedTokensAfter *int64
Usage json.RawMessage
Details json.RawMessage
}
CompactionResult describes the summary produced by Pi and the first entry it kept. Pi supplies EstimatedTokensAfter, Usage and extension-specific Details when available.
type ContextUsage ¶
type ContextUsage struct {
Tokens *int64 `json:"tokens"`
ContextWindow int64 `json:"contextWindow"`
Percent *float64 `json:"percent"`
}
ContextUsage describes the current model context, with nil values when Pi cannot estimate how much of it is occupied.
type DispatchError ¶
DispatchError means the command reached write admission and its outcome is unknown. Sent is true only when the entire frame was written or a response was observed. A false Sent on this error does not exclude a partial write. Do not automatically retry.
func (*DispatchError) Error ¶
func (e *DispatchError) Error() string
func (*DispatchError) Unwrap ¶
func (e *DispatchError) Unwrap() error
type Entries ¶
Entries contains entries in native append order. LeafID identifies the active branch's leaf and is nil when no leaf is selected.
type Entry ¶
type Entry struct {
ID string `json:"id"`
ParentID *string `json:"parentId"`
Type string `json:"type"`
Timestamp string `json:"timestamp"`
Raw json.RawMessage `json:"-"`
}
Entry contains common native session entry fields. Raw retains the full entry, including type-specific content.
func (*Entry) UnmarshalJSON ¶
type Event ¶
type Event struct {
Type string
Raw json.RawMessage
}
Event preserves one complete non-response RPC record, including unknown fields.
type ForkMessage ¶
ForkMessage identifies a user message Pi offers as a fork point.
type HistoryEntry ¶
type HistoryEntry struct {
Type string `json:"type"`
ID string `json:"id"`
ParentID *string `json:"parentId"`
Raw json.RawMessage `json:"-"`
}
HistoryEntry preserves one saved entry and its native branch links. Legacy entries can omit ID and ParentID. Raw includes all fields and distinguishes an explicit null parent from a missing parent.
type HistoryScope ¶
HistoryScope selects one explicit session directory and workspace. Both paths must be absolute. Only immediate regular .jsonl files are considered.
type HistoryWindow ¶
type HistoryWindow struct {
Offset, Limit int
}
HistoryWindow selects a range of records by their position in the local file. Offset is zero-based and Limit zero reads to the end of the file. The header, blank lines and a partial trailing write do not count.
type Image ¶
type Image struct {
Type string `json:"type"`
Data string `json:"data"`
MIMEType string `json:"mimeType"`
}
Image holds the native base64 data and MIME type. Type must be "image".
type ModelSelection ¶
type ModelSelection struct {
Model json.RawMessage
ThinkingLevel string
IsScoped bool
}
ModelSelection is Pi's result after cycling the active model. Model retains the full native object, including provider-specific fields.
type Options ¶
type Options struct {
Command string
Args []string
Cwd string
Env []string // KEY=value entries overlay the process environment
SessionDir string
SessionFile string // an existing file, used with ResumeID
ResumeID string
Provider string
Model string
ThinkingLevel string
AdditionalSystemPrompt string // literal text
NoTools bool
NoExtensions bool
ExtensionPaths []string // explicit -e paths or builtin:<name>
ExtraArgs []string
Stderr io.Writer // diagnostics; nil discards output
}
Options configure a native Pi process. Args precede the RPC arguments (for launchers such as node). ExtraArgs are resource controls; options that can start work or select a session or another protocol are excluded.
type PromptResult ¶
type PromptResult struct {
Disposition string `json:"disposition"`
}
PromptResult describes native acceptance. It does not prove execution or consumption.
type QueueMode ¶
type QueueMode string
QueueMode is a native Pi steering or follow-up delivery mode.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session owns the two protocol streams and, for Open, the local process.
func Attach ¶
func Attach(ctx context.Context, input io.WriteCloser, output io.ReadCloser, expectedID string) (*Session, error)
Attach takes ownership of input and output and performs the same get_state handshake as Open. Closing each endpoint must unblock any operation on it.
func Open ¶
Open starts one local Pi RPC process. Its lifetime belongs to Session; cancellation of ctx after the initial handshake does not stop it.
func (*Session) Abort ¶
Abort waits for the native abort response. Queue continuation follows Pi's own scheduling policy.
func (*Session) AbortBash ¶
AbortBash asks Pi to stop the running user shell command and waits for its acknowledgement. A caller still waiting in Bash receives the command's final result separately.
func (*Session) AbortRetry ¶
AbortRetry asks Pi to stop its current retry. Canceling the wait after dispatch leaves the outcome unknown.
func (*Session) AvailableModels ¶
AvailableModels reads the configured models as complete native model objects.
func (*Session) AvailableThinkingLevels ¶
AvailableThinkingLevels reads the selected model's discrete native levels.
func (*Session) Bash ¶
func (s *Session) Bash(ctx context.Context, command string, excludeFromContext *bool) (BashResult, error)
Bash asks the Pi process to execute a user shell command in the session workspace. A nil excludeFromContext uses Pi's default. Pass true to keep the result out of the model context. Canceling ctx ends the caller's wait. A dispatched command can continue until it exits or AbortBash stops it.
func (*Session) ClearQueue ¶
func (s *Session) ClearQueue(ctx context.Context) (ClearedQueue, error)
ClearQueue removes queued steering and follow-up messages in the attached Pi process. The active turn continues. Canceling the wait after dispatch leaves the outcome unknown.
func (*Session) Close ¶
Close releases resources once. An owned process receives stdin EOF before forced termination.
func (*Session) CloseAndDiscard ¶
CloseAndDiscard releases the session and discards any unread events.
func (*Session) Commands ¶
Commands reads the extension commands, prompt templates, and skills Pi exposes.
func (*Session) Compact ¶
Compact asks the attached Pi process to abort any active turn and compact its conversation. Pi may call the model to generate a summary. Pass an empty string to use Pi's default instructions. Canceling the wait after dispatch lets Pi continue compaction.
func (*Session) CycleModel ¶
func (s *Session) CycleModel(ctx context.Context) (*ModelSelection, error)
CycleModel advances to the next model in Pi's rotation. A nil selection with a nil error means Pi returned no alternative.
func (*Session) CycleThinkingLevel ¶
CycleThinkingLevel advances the current model's thinking level. A nil level with a nil error means Pi returned no alternative.
func (*Session) Entries ¶
Entries reads append-order records from the current session. Pass an empty since to start from the beginning, or the last received entry ID to read strictly after it. LeafID describes the active branch independently of since. An empty result means there were no new entries at the time of the call.
func (*Session) ExportHTML ¶
ExportHTML asks Pi to write the session as HTML and returns the path from Pi's filesystem. An empty outputPath lets Pi choose the destination. Pi may finish writing the file after the caller cancels the wait.
func (*Session) ForkMessages ¶
func (s *Session) ForkMessages(ctx context.Context) ([]ForkMessage, error)
ForkMessages lists the current session's fork points in Pi's order.
func (*Session) LastAssistantText ¶
LastAssistantText reads Pi's selection of the last assistant text. It returns nil when Pi omits the text or reports null.
func (*Session) Messages ¶
Messages reads the current model-facing conversation. Each message retains its complete native JSON.
func (*Session) Prompt ¶
func (s *Session) Prompt(ctx context.Context, message string, images []Image, streamingBehavior string) (PromptResult, error)
Prompt starts work when idle. While streaming Pi requires "steer" or "followUp" to queue it.
func (*Session) Receive ¶
Receive consumes the next native event. Already accepted events remain available after Close.
func (*Session) RespondUI ¶
func (s *Session) RespondUI(ctx context.Context, response UIResponse) error
RespondUI writes a native one-way response. Success confirms the complete frame was written. Pi may already have dropped the request and does not ack.
func (*Session) SetAutoCompaction ¶
SetAutoCompaction asks Pi to update its global setting for automatic context compaction. Canceling the wait after dispatch leaves the outcome unknown.
func (*Session) SetAutoRetry ¶
SetAutoRetry asks Pi to update its global setting for automatic retry of transient errors. Canceling the wait after dispatch leaves the outcome unknown.
func (*Session) SetFollowUpMode ¶
SetFollowUpMode sets how Pi delivers follow-up input after work completes. Read State to observe the effective mode.
func (*Session) SetSessionName ¶
SetSessionName asks Pi to rename the current session. Canceling the wait after dispatch leaves Pi free to apply the name.
func (*Session) SetSteeringMode ¶
SetSteeringMode sets how Pi delivers queued steering input between turns. Read State to observe the effective mode.
func (*Session) SetThinkingLevel ¶
SetThinkingLevel reports native acceptance. State reports the value actually selected.
func (*Session) State ¶
State reads Pi's current state. A changed native identity invalidates this attachment.
func (*Session) Stats ¶
func (s *Session) Stats(ctx context.Context) (SessionStats, error)
Stats reads session statistics. A different identity invalidates the session.
type SessionHistory ¶
type SessionHistory struct {
Info SessionInfo
Entries []HistoryEntry
NextOffset int
HasMore bool
TrailingPartial bool
}
SessionHistory contains entries in original file order, including branches. With HasMore, NextOffset can continue reading this file from disk. Queries are independent reads and do not provide a snapshot across calls. A malformed final record without a newline sets TrailingPartial and is excluded.
func ReadSessionHistory ¶
func ReadSessionHistory(ctx context.Context, scope HistoryScope, sessionID string, window HistoryWindow) (SessionHistory, error)
ReadSessionHistory reads saved entries without launching Pi or following ParentSession. Its offset is independent of the live get_entries cursor.
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"id"`
Cwd string `json:"cwd"`
Version int `json:"version"`
Timestamp string `json:"timestamp"`
ParentSession string `json:"parentSession"`
SessionFile string `json:"-"`
Raw json.RawMessage `json:"-"`
}
SessionInfo contains metadata from a saved Pi session header. Version is 1 when the native legacy header omitted it. Raw preserves the original header.
func GetSessionInfo ¶
func GetSessionInfo(ctx context.Context, scope HistoryScope, sessionID string) (SessionInfo, error)
GetSessionInfo reads header metadata for an exact saved session ID.
func ListSessions ¶
func ListSessions(ctx context.Context, scope HistoryScope) ([]SessionInfo, error)
ListSessions discovers sessions by their saved header ID, ordered by filename. It skips files without a valid header and files outside the requested workspace.
type SessionStats ¶
type SessionStats struct {
SessionID string `json:"sessionId"`
SessionFile string `json:"sessionFile"`
UserMessages int64 `json:"userMessages"`
AssistantMessages int64 `json:"assistantMessages"`
ToolCalls int64 `json:"toolCalls"`
ToolResults int64 `json:"toolResults"`
TotalMessages int64 `json:"totalMessages"`
Tokens TokenUsage `json:"tokens"`
Cost float64 `json:"cost"`
ContextUsage *ContextUsage `json:"contextUsage"`
Raw json.RawMessage `json:"-"`
}
SessionStats contains Pi's session-wide totals. ContextUsage, when present, describes the current model context. Raw retains the full native data object.
type State ¶
type State struct {
SessionID string `json:"sessionId"`
SessionFile string `json:"sessionFile"`
ThinkingLevel string `json:"thinkingLevel"`
IsStreaming bool `json:"isStreaming"`
SteeringMode QueueMode `json:"steeringMode"`
FollowUpMode QueueMode `json:"followUpMode"`
PendingMessageCount int `json:"pendingMessageCount"`
Model json.RawMessage `json:"model"`
Raw json.RawMessage `json:"-"`
}
State is a snapshot returned by get_state. Raw preserves the entire native data value.
type TokenUsage ¶
type TokenUsage struct {
Input int64 `json:"input"`
Output int64 `json:"output"`
CacheRead int64 `json:"cacheRead"`
CacheWrite int64 `json:"cacheWrite"`
Total int64 `json:"total"`
}
TokenUsage holds the native token totals.
type Tree ¶
Tree contains native root nodes, including abandoned branches, and the optional active leaf identity.
type TreeNode ¶
type TreeNode struct {
Entry Entry `json:"entry"`
Children []TreeNode `json:"children"`
Label *string `json:"label"`
LabelTimestamp *string `json:"labelTimestamp"`
}
TreeNode mirrors one native session tree node.
type UIRequest ¶
type UIRequest struct {
ID string `json:"id"`
Method string `json:"method"`
Title string `json:"title"`
Message string `json:"message"`
Options []string `json:"options"`
Placeholder string `json:"placeholder"`
Prefill string `json:"prefill"`
TimeoutMS int64 `json:"timeout"`
Raw json.RawMessage `json:"-"`
}
UIRequest describes a UI frame emitted by an extension. Methods such as notify are one-way. Dialog methods select, confirm, input and editor expect a response with the original ID. Raw preserves fields outside this view.
type UIResponse ¶
type UIResponse struct {
ID string `json:"id"`
Value *string `json:"value,omitempty"`
Confirmed *bool `json:"confirmed,omitempty"`
Canceled bool `json:"cancelled,omitempty"` //nolint:misspell // Pi wire field.
}
UIResponse answers a dialog. Set exactly one of Value, Confirmed or Canceled.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
tests
|
|
|
simulation
Package pisim exercises the public Pi SDK against native recordings.
|
Package pisim exercises the public Pi SDK against native recordings. |