pi

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Native Pi client

Open creates a fresh session in a new Pi process with a dedicated stdio connection. Opening with ResumeID starts another process and restores the specified identity. Attach takes ownership of two closable streams. Both wait for get_state to return a session ID. Use a deadline for that handshake.

A Session stays bound to its handshake ID until close. The commands new_session, switch_session, fork, and clone are prohibited on a bound connection because they can change its identity. If Pi reports a conflicting ID, the handle closes, ID() keeps the handshake value, and further writes fail. ForkMessages sends only the read-only get_fork_messages query. Current session operations

Read events with Receive. It delivers non-response records in wire order and preserves unknown fields. Each inbound JSONL record must fit within the 64 MiB reader limit. Close releases the streams and process while keeping received events available to drain. Use CloseAndDiscard to release unread events when you stop consuming them. An owned process gets stdin EOF and has two seconds to exit before the client kills it.

Command IDs correlate concurrent responses. The Prompt disposition records whether Pi started, queued, or handled the input. agent_end closes one low-level run. Use agent_settled to observe the end of automatic work after a run starts. Abort returns the native command response. The event stream still carries the run outcome. A CommandError preserves the failure response. A DispatchError means the outcome is unknown after write admission, which can happen if the waiting context is canceled. Check the session before deciding whether to submit again. Native operations

Set ResumeID to the complete native ID. The launcher checks the ID and workspace in the existing session header, passes the full filename to Pi, and verifies the ID in get_state. Set SessionDir when Pi settings select custom storage, or give the exact SessionFile. Resume requires a persisted session file. Resume lookup

Read saved sessions

Set absolute paths for the workspace and the session directory in HistoryScope. Use ListSessions to discover IDs, GetSessionInfo to inspect a header, and ReadSessionHistory to read entries in file order. These calls read one directory without starting Pi or migrating older records. If a history page has more entries, pass its NextOffset to the next disk read. The live get_entries command uses native entry IDs as cursors. Saved history API

Explicit extensions

Set Options.ExtensionPaths to load extensions explicitly with -e. NoExtensions disables automatic discovery and leaves explicit paths available. Session.Commands reports the commands, prompt templates, and skills Pi currently exposes.

Decode an extension UI event with Event.UIRequest. Use its original dialog ID with Session.RespondUI. Pi uses a one-way response, so a successful call confirms the complete frame write. The next native events carry the outcome.

MCP servers in the unified adapter

Pass the complete list of application-managed MCP servers in agent.OpenOptions.MCPServers. Repeat the list on Resume. Pi 1.6.0 connects to stdio and Streamable HTTP servers and exposes their tools directly to the model. HTTP authentication can use literal headers, file-backed values, or environment variables available to the Pi process.

Pi also reads its user MCP file and trusted project MCP file. A server from either file takes precedence over a registration with the same name. Pi treats hyphens and underscores as equivalent in server names. The adapter rejects duplicate registrations under this rule.

Open and Resume confirm extension initialization. Pi connects MCP servers in the background. Use Pi's MCP connection status or a successful tool result to verify that a server is ready. Pi MCP configuration

Protocol source

The bindings use the MIT-licensed Pi v1.6.0 protocol at Git commit faac585884ae2c013a6b1400f3e9e77f10b34bac. Pi release, MIT license

Upstream file SHA-256
packages/coding-agent/docs/rpc.md 54e29df00e080c962df4fbb516dc441a9ce6805287bea61d45f3c99f92078446
packages/coding-agent/docs/rpc-commands.md 2bf20a4e7690db5c3407948efe0b374b444df7707ff7b238e2e80c46025bb440
packages/coding-agent/docs/json.md f103191816fdcf3627dfc98b89acad8a28eee737697130ddaeb2581131213543
Native RPC types be06a1d53916e03e9274cce9e4833692b235494e4047f1f7139d7f0147daae1a
Official RpcClient a34c9eb4937bf3b526128c9a2032cc3295504996a14bf204e4a17e5bb55dcf7f
packages/coding-agent/docs/session-format.md 4f8fc42179b332bcf71fe4c85cc95d914853ff7486d68742954a45316b512a4a

The tests in this package use synthetic peers.

Documentation

Overview

Package pi controls a Pi coding-agent v1.6.0 subprocess through its JSONL RPC protocol.

Index

Constants

This section is empty.

Variables

View Source
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.

View Source
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

type ClearedQueue struct {
	Steering []string
	FollowUp []string
}

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

type DispatchError struct {
	Sent bool
	Err  error
}

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

type Entries struct {
	Entries []Entry
	LeafID  *string
}

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

func (e *Entry) UnmarshalJSON(raw []byte) error

type Event

type Event struct {
	Type string
	Raw  json.RawMessage
}

Event preserves one complete non-response RPC record, including unknown fields.

func (Event) UIRequest

func (e Event) UIRequest() (UIRequest, error)

UIRequest decodes the original native extension UI event.

type ForkMessage

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

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

type HistoryScope struct {
	Cwd        string
	SessionDir string
}

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.

const (
	QueueAll        QueueMode = "all"
	QueueOneAtATime QueueMode = "one-at-a-time"
)

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

func Open(ctx context.Context, options Options) (*Session, error)

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

func (s *Session) Abort(ctx context.Context) error

Abort waits for the native abort response. Queue continuation follows Pi's own scheduling policy.

func (*Session) AbortBash

func (s *Session) AbortBash(ctx context.Context) error

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

func (s *Session) AbortRetry(ctx context.Context) error

AbortRetry asks Pi to stop its current retry. Canceling the wait after dispatch leaves the outcome unknown.

func (*Session) AvailableModels

func (s *Session) AvailableModels(ctx context.Context) ([]json.RawMessage, error)

AvailableModels reads the configured models as complete native model objects.

func (*Session) AvailableThinkingLevels

func (s *Session) AvailableThinkingLevels(ctx context.Context) ([]string, error)

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

func (s *Session) Close() error

Close releases resources once. An owned process receives stdin EOF before forced termination.

func (*Session) CloseAndDiscard

func (s *Session) CloseAndDiscard() error

CloseAndDiscard releases the session and discards any unread events.

func (*Session) Commands

func (s *Session) Commands(ctx context.Context) ([]Command, error)

Commands reads the extension commands, prompt templates, and skills Pi exposes.

func (*Session) Compact

func (s *Session) Compact(ctx context.Context, customInstructions string) (CompactionResult, error)

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

func (s *Session) CycleThinkingLevel(ctx context.Context) (*string, error)

CycleThinkingLevel advances the current model's thinking level. A nil level with a nil error means Pi returned no alternative.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

func (*Session) Entries

func (s *Session) Entries(ctx context.Context, since string) (Entries, error)

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) Err

func (s *Session) Err() error

func (*Session) ExportHTML

func (s *Session) ExportHTML(ctx context.Context, outputPath string) (string, error)

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) FollowUp

func (s *Session) FollowUp(ctx context.Context, message string, images []Image) (PromptResult, error)

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) ID

func (s *Session) ID() string

func (*Session) LastAssistantText

func (s *Session) LastAssistantText(ctx context.Context) (*string, error)

LastAssistantText reads Pi's selection of the last assistant text. It returns nil when Pi omits the text or reports null.

func (*Session) Messages

func (s *Session) Messages(ctx context.Context) ([]json.RawMessage, error)

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

func (s *Session) Receive(ctx context.Context) (Event, error)

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

func (s *Session) SetAutoCompaction(ctx context.Context, enabled bool) error

SetAutoCompaction asks Pi to update its global setting for automatic context compaction. Canceling the wait after dispatch leaves the outcome unknown.

func (*Session) SetAutoRetry

func (s *Session) SetAutoRetry(ctx context.Context, enabled bool) error

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

func (s *Session) SetFollowUpMode(ctx context.Context, mode QueueMode) error

SetFollowUpMode sets how Pi delivers follow-up input after work completes. Read State to observe the effective mode.

func (*Session) SetModel

func (s *Session) SetModel(ctx context.Context, provider, id string) error

func (*Session) SetSessionName

func (s *Session) SetSessionName(ctx context.Context, name string) error

SetSessionName asks Pi to rename the current session. Canceling the wait after dispatch leaves Pi free to apply the name.

func (*Session) SetSteeringMode

func (s *Session) SetSteeringMode(ctx context.Context, mode QueueMode) error

SetSteeringMode sets how Pi delivers queued steering input between turns. Read State to observe the effective mode.

func (*Session) SetThinkingLevel

func (s *Session) SetThinkingLevel(ctx context.Context, level string) error

SetThinkingLevel reports native acceptance. State reports the value actually selected.

func (*Session) State

func (s *Session) State(ctx context.Context) (State, error)

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.

func (*Session) Steer

func (s *Session) Steer(ctx context.Context, message string, images []Image) (PromptResult, error)

func (*Session) Tree

func (s *Session) Tree(ctx context.Context) (Tree, error)

Tree reads the current session tree with its native active leaf.

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

type Tree struct {
	Roots  []TreeNode
	LeafID *string
}

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.

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.

Jump to

Keyboard shortcuts

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