cli

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 98 Imported by: 0

Documentation

Overview

Package cli is the pig command line as a library: Main runs it for an argument list, as Pi's main(args, options) does (main.ts:573).

pig divergence (D2): refuse the `pi` name to protect Pi's command identity.

pig: Go-native port of pi-coding-agent.

Distinct binary name and config root from upstream pi to avoid PATH collisions and shared-config corruption. See codingagent.ConfigRoot() for the on-disk layout (defaults to ~/.pig, override with $PIG_HOME).

Usage:

pig [options] [prompt]

Options:

--model <provider/model>    Model to use (default: from settings)
--agent <name>              Agent definition to load from <config>/agents/
--print <prompt>            Print mode: send prompt and print response, then exit
--no-extensions             Disable all extensions
-e <path>                   Load extension (can be repeated)
--skill <name>              Load a skill
--cwd <dir>                 Working directory (default: current dir)
--agent-dir <dir>           Agent config directory (default: <config>/agent)
--version                   Print version and exit

Ports packages/coding-agent/src/core/resource-loader.ts

Ports packages/coding-agent/src/modes/rpc/rpc-mode.ts

Ports packages/coding-agent/src/modes/rpc/rpc-mode.ts

Ports packages/coding-agent/src/modes/json-event.ts.

Ports packages/coding-agent/src/modes/rpc/rpc-mode.ts

Ports packages/coding-agent/src/modes/rpc/rpc-mode.ts

Startup timing instrumentation for pig.

Activated by setting PIG_STARTUP_TRACE=1. Prints structured timing to stderr showing wall-clock elapsed from process start for each startup. Uses Go's monotonic clock via time.Since.

Usage:

PIG_STARTUP_TRACE=1 pig --model github-copilot/gpt-5-mini

Output:

[startup] flags-parsed          0ms
[startup] services-init         2ms
[startup] model-resolved        3ms
[startup] extensions-loaded    25ms
[startup] session-created      28ms
[startup] interactive-ready   130ms

This is the official profiling mechanism. Do NOT add ad-hoc fmt.Fprintf timing to main.go or interactive.go: use this.

Index

Constants

View Source
const (
	PigVersion      = coding.PigVersion
	UpstreamVersion = coding.UpstreamVersion
	// UpstreamPackageVersion is what Pi's own `--version` and user agent report.
	UpstreamPackageVersion = coding.UpstreamPackageVersion
	Version                = coding.Version
)

PigVersion is pig's own release line. UpstreamVersion is the pi build this build targets (a release tag, or a pinned commit as 1.1.0+42a3497d), and UpstreamPackageVersion the version that build's package.json files report. The literals live in internal/coding/pigversion/pigversion.go, generated from .upstream/pin; coding/upstream.go aliases it, so the parity runner (and this constant) can import it without depending on package main.

Variables

View Source
var Build = "dev"

Build is the git commit/tag, set via -ldflags at build time.

View Source
var PigletBinaryVersion string

pig divergence (D39): PigletBinaryVersion is the baked release identity.

Functions

func CreateAuthCheckModelRuntime

func CreateAuthCheckModelRuntime(ctx context.Context, credentials ai.CredentialStore, agentDir string) (*codingagent.RequestAuthRuntime, error)

CreateAuthCheckModelRuntime mirrors upstream createAuthCheckModelRuntime: an in-memory models store, no catalog refresh, and no availability pass.

func GetAuthCommandName

func GetAuthCommandName(kind AuthCommandKind) string

GetAuthCommandName mirrors upstream getAuthCommandName.

func GetAuthCommandUsage

func GetAuthCommandUsage(kind AuthCommandKind) string

GetAuthCommandUsage mirrors upstream getAuthCommandUsage.

func GetAuthCredential

func GetAuthCredential(auth *ai.AuthResult) string

GetAuthCredential mirrors upstream getAuthCredential: the resolved API key, otherwise the token of an `Authorization: Bearer` header.

func GetProviderCredential

func GetProviderCredential(ctx context.Context, providerID string, runtime *codingagent.RequestAuthRuntime, credentials ai.CredentialStore, refresh bool) (string, error)

GetProviderCredential mirrors upstream getProviderCredential: without refresh a stored OAuth access token is returned as stored.

func IsAuthCommandHelp

func IsAuthCommandHelp(args []string) bool

IsAuthCommandHelp mirrors upstream isAuthCommandHelp.

func Main

func Main(args []string, options *MainOptions)

Main runs the pig command line for args, the arguments after the program name, as Pi's main(args, options) does (main.ts:573). The default and experimental executables call it with args and no options.

func ResolveCredentialForPrint

func ResolveCredentialForPrint(ctx context.Context, flags Args, rawArgs []string, runtime *codingagent.RequestAuthRuntime, kind AuthCommandKind, minExpiryMs *float64) (string, error)

ResolveCredentialForPrint resolves one configured provider credential for `auth print-api-key` or `auth print-bearer-token`. It resolves through the normal request-auth path, which refreshes and persists OAuth credentials with less than five minutes remaining. An API key is printed only from a provider not configured with OAuth; a bearer token only from one that is.

Types

type Args

type Args struct {
	Model        string
	Print        bool
	NoExtensions bool
	// NoMcp disables the built-in MCP extension for this run (--no-mcp).
	NoMcp      bool
	Extensions []string
	Skills     []string
	Version    bool
	Help       bool
	// Session selection flags.
	Resume   bool // --resume always opens the startup picker; use --session for path or ID
	Continue bool // --continue: load most recent session non-interactively
	// Messages are the positional arguments (upstream args.messages): the prompt in interactive mode.
	Messages []string
	// Mode selects the output mode: text (default), json, or rpc.
	// Mirrors upstream --mode.
	Mode string

	// Verbose forces verbose startup output (overrides quietStartup setting).
	// Mirrors upstream --verbose (args.ts:153-154, 239).
	Verbose bool

	// Provider overrides the default provider name (e.g. "openai", "anthropic").
	// Mirrors upstream --provider (args.ts:79).
	Provider string
	// SystemPrompt selects explicit prompt text or a file. An explicitly empty option suppresses SYSTEM.md discovery and retains the built-in prompt.
	SystemPrompt string

	// AppendSystemPrompt appends text to the system prompt (repeatable).
	// Mirrors upstream --append-system-prompt (args.ts:86).
	AppendSystemPrompt []string
	// Thinking sets the thinking level: off, minimal, low, medium, high, xhigh, max.
	// Mirrors upstream --thinking (args.ts:118).
	Thinking string
	// NoSession disables session persistence (ephemeral).
	// Mirrors upstream --no-session (args.ts:92).
	NoSession bool
	// Session specifies a session file path or partial UUID.
	// Mirrors upstream --session (args.ts:93).
	Session string
	// Fork forks a specific session into a new session.
	// Mirrors upstream --fork (args.ts:94).
	Fork string
	// SessionDir overrides the session storage directory.
	// Mirrors upstream --session-dir (args.ts:95).
	SessionDir string
	// SessionID specifies an exact session ID to use or create.
	// Mirrors upstream --session-id (args.ts:107, v0.76.0).
	SessionID string
	// SessionIDSet distinguishes an omitted --session-id from an explicitly empty value, which validateSessionIdFlags rejects.
	SessionIDSet bool

	// Name is the raw Session display name from --name / -n.
	Name string
	// NameSet distinguishes an omitted --name from an explicitly empty value.
	NameSet bool
	// NoTools disables all tools.
	// Mirrors upstream --no-tools / -nt (args.ts:98).
	NoTools bool
	// NoBuiltinTools disables built-in tools while leaving extension/custom tools available.
	// Mirrors upstream --no-builtin-tools / -nbt (args.ts:100 in v0.70.0).
	NoBuiltinTools bool
	// Tools is the allowlist from the last --tools / -t (args.ts:147-151). nil means the flag is absent; a non-nil empty list is an explicit empty allowlist.
	Tools []string
	// ExcludeTools is the denylist from the last --exclude-tools / -xt (args.ts:152-156).
	ExcludeTools []string
	// ListModels prints available models and exits. Optional search pattern.
	// Mirrors upstream --list-models (args.ts:147).
	ListModels    string
	ListModelsAll bool // --list-models without a nonempty filter
	// NoSkills disables skill discovery.
	// Mirrors upstream --no-skills (args.ts:107).
	NoSkills bool
	// PromptTemplates lists prompt template paths (repeatable).
	// Mirrors upstream --prompt-template (args.ts:110).
	PromptTemplates []string
	// NoPromptTemplates disables prompt template discovery.
	// Mirrors upstream --no-prompt-templates (args.ts:113).
	NoPromptTemplates bool
	// Themes lists theme paths (repeatable).
	// Mirrors upstream --theme (args.ts:114).
	Themes []string
	// NoThemes disables theme discovery.
	// Mirrors upstream --no-themes (args.ts:115).
	NoThemes bool
	// NoContextFiles disables AGENTS.md/CLAUDE.md discovery.
	// Mirrors upstream --no-context-files (args.ts:116).
	NoContextFiles bool
	// Export exports a session file to HTML and exits.
	// Mirrors upstream --export (args.ts:106).
	Export string
	// APIKey overrides the API key.
	// Mirrors upstream --api-key (args.ts:82).
	APIKey string
	// Offline disables startup network operations.
	// Mirrors upstream --offline (args.ts:150).
	Offline bool
	// NoStdin skips the startup read of piped stdin, so a stdin pipe whose writer never closes does not block startup.
	// pig divergence (D150): Pi has no such flag.
	NoStdin bool
	// ProjectTrustOverride controls project-local resource loading for this run.
	// nil uses saved/default trust; true is --approve; false is --no-approve.
	ProjectTrustOverride *bool
	// FileArgs holds @file arguments (files included in prompt).
	// Mirrors upstream args.fileArgs (args.ts:160).
	FileArgs []string
	// Models comma-separated model patterns for Ctrl+P cycling.
	// Mirrors upstream --models (args.ts:96).
	Models []string
	// UnknownFlags preserves flags not claimed by the core parser so
	// extensions can consume them later.
	UnknownFlags map[string]any
	// UnknownFlagOrder lists the UnknownFlags names in command-line order, the insertion order of upstream's unknownFlags Map.
	UnknownFlagOrder []string
	// UseTheme and TuiMode override the theme and TUI mode for this run. UseTheme is nil when omitted; an explicitly empty name is a selection.
	UseTheme *string
	TuiMode  string
	// Diagnostics mirrors Pi parseArgs diagnostics. Any error exits before
	// version or mode handling.
	Diagnostics []argDiagnostic
	// contains filtered or unexported fields
}

Args holds parsed command-line arguments, upstream's Args interface (cli/args.ts:13). Mirrors upstream cli/args.ts:parseArgs.

type AuthCheckReason

type AuthCheckReason string

AuthCheckReason mirrors upstream AuthCheckReason.

const (
	AuthCheckProviderNotFound         AuthCheckReason = "provider_not_found"
	AuthCheckCredentialsNotConfigured AuthCheckReason = "credentials_not_configured"
	AuthCheckCredentialNotAvailable   AuthCheckReason = "credential_not_available"
	AuthCheckInvalidState             AuthCheckReason = "invalid_state"
)

type AuthCheckResult

type AuthCheckResult struct {
	Status   AuthCheckStatus   `json:"status"`
	Provider string            `json:"provider"`
	Reason   AuthCheckReason   `json:"reason,omitempty"`
	AuthType ai.CredentialType `json:"authType,omitempty"`
}

AuthCheckResult mirrors upstream AuthCheckResult; JSON field order matches the upstream object literals.

func CheckProviderAuth

func CheckProviderAuth(ctx context.Context, flags Args, rawArgs []string, runtime *codingagent.RequestAuthRuntime, refresh bool) (AuthCheckResult, error)

CheckProviderAuth mirrors upstream checkProviderAuth.

type AuthCheckStatus

type AuthCheckStatus string

AuthCheckStatus mirrors upstream AuthCheckStatus.

const (
	AuthCheckReady    AuthCheckStatus = "ready"
	AuthCheckNotReady AuthCheckStatus = "not_ready"
	AuthCheckInvalid  AuthCheckStatus = "invalid"
)

type AuthCommand

type AuthCommand struct {
	Kind        AuthCommandKind
	Args        []string
	JSON        bool
	Credentials bool
	NoRefresh   bool
	// MinExpiryMs is set only by print-bearer-token --min-expiry.
	MinExpiryMs *float64
}

AuthCommand mirrors upstream AuthCommand.

func ParseAuthCommand

func ParseAuthCommand(args []string) (*AuthCommand, error)

ParseAuthCommand mirrors upstream parseAuthCommand. It returns nil for arguments that are not an auth command.

type AuthCommandError

type AuthCommandError struct{ Message string }

AuthCommandError is a user-facing auth command failure.

func (*AuthCommandError) Error

func (e *AuthCommandError) Error() string

type AuthCommandKind

type AuthCommandKind string

AuthCommandKind mirrors upstream AuthCommandKind.

const (
	AuthCommandCheck       AuthCommandKind = "check"
	AuthCommandAPIKey      AuthCommandKind = "api_key"
	AuthCommandBearerToken AuthCommandKind = "bearer_token"
)

type AuthCommandTarget

type AuthCommandTarget struct {
	Provider string
	Model    string
}

AuthCommandTarget is the provider/model pair an auth command resolves.

func ValidateAuthCommandArgs

func ValidateAuthCommandArgs(flags Args, _ []string, kind AuthCommandKind) (AuthCommandTarget, error)

ValidateAuthCommandArgs mirrors upstream validateAuthCommandArgs. The second argument, the arguments parsed into flags, is not read: flags record whether --api-key was given.

type MainOptions

type MainOptions struct {
	// ExtensionFactories are the compiled-in extensions an embedding program adds after the built-in ones (main.ts:575). Only the program's own main passes them (docs/specs/extension-factory-trust.md).
	ExtensionFactories []extension.InlineExtension
}

MainOptions are the options of Main (main.ts MainOptions).

type RPCAbortBashCommand

type RPCAbortBashCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCAbortBashCommand is rpc-types.ts { id?: string; type: "abort_bash" }.

type RPCAbortCommand

type RPCAbortCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCAbortCommand cancels the current operation. Upstream: rpc-types.ts:28 { type: "abort" }

type RPCAbortRetryCommand

type RPCAbortRetryCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

type RPCBashCommand

type RPCBashCommand struct {
	ID                 rpcRequestID `json:"id,omitempty"`
	Type               string       `json:"type"`
	Command            string       `json:"command"`
	ExcludeFromContext *bool        `json:"excludeFromContext,omitempty"`
}

RPCBashCommand executes a bash command outside the LLM agent loop. Upstream: rpc-types.ts { type: "bash"; command: string; excludeFromContext?: boolean }

type RPCBashExecutionUpdate

type RPCBashExecutionUpdate struct {
	Type  string       `json:"type"`
	ID    rpcRequestID `json:"id,omitempty"`
	Delta string       `json:"delta"`
}

type RPCBashResult

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

RPCBashResult is the response payload for the bash command. Mirrors coding.BashResult.

type RPCCancelledResult

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

type RPCClearQueueCommand

type RPCClearQueueCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCClearQueueCommand removes queued steering and follow-up messages.

type RPCClearQueueData

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

type RPCCloneCommand

type RPCCloneCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

type RPCCommand

type RPCCommand interface {
	// contains filtered or unexported methods
}

RPCCommand is the closed union of rpc-types.ts RpcCommand: one struct per member, RPC<Type>Command, whose Type member is the member's "type" literal (an RPCCommandType constant). decodeRPCCommand reads one member from a command line.

type RPCCommandEnvelope

type RPCCommandEnvelope struct {
	ID rpcRequestID `json:"id,omitempty"`
	// Type is the "type" member when it is a JSON string; TypeValue is that member as Pi re-emits it, nil when absent.
	Type      RPCCommandType  `json:"type"`
	TypeValue json.RawMessage `json:"-"`
	Raw       json.RawMessage `json:"-"` // full original bytes, set by parseRPCCommand
}

RPCCommandEnvelope is the raw JSON wrapper. The Type field selects which concrete command struct to unmarshal into.

func (*RPCCommandEnvelope) UnmarshalJSON

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

UnmarshalJSON reads the "id" and "type" members as rpc-mode.ts reads command.id and command.type from JSON.parse output: names match exactly, a later duplicate wins, and a non-object command has neither member. Members alias data during the call, so an image-sized prompt member is scanned but never copied; the retained values are copies.

type RPCCommandType

type RPCCommandType string

RPCCommandType is the "type" member of an RpcCommand: the closed union of command names in rpc-types.ts RpcCommand.

const (
	RPCCommandPrompt                     RPCCommandType = "prompt"
	RPCCommandSteer                      RPCCommandType = "steer"
	RPCCommandFollowUp                   RPCCommandType = "follow_up"
	RPCCommandAbort                      RPCCommandType = "abort"
	RPCCommandClearQueue                 RPCCommandType = "clear_queue"
	RPCCommandNewSession                 RPCCommandType = "new_session"
	RPCCommandGetState                   RPCCommandType = "get_state"
	RPCCommandSetModel                   RPCCommandType = "set_model"
	RPCCommandCycleModel                 RPCCommandType = "cycle_model"
	RPCCommandGetAvailableModels         RPCCommandType = "get_available_models"
	RPCCommandSetThinkingLevel           RPCCommandType = "set_thinking_level"
	RPCCommandCycleThinkingLevel         RPCCommandType = "cycle_thinking_level"
	RPCCommandGetAvailableThinkingLevels RPCCommandType = "get_available_thinking_levels"
	RPCCommandSetSteeringMode            RPCCommandType = "set_steering_mode"
	RPCCommandSetFollowUpMode            RPCCommandType = "set_follow_up_mode"
	RPCCommandCompact                    RPCCommandType = "compact"
	RPCCommandSetAutoCompaction          RPCCommandType = "set_auto_compaction"
	RPCCommandSetAutoRetry               RPCCommandType = "set_auto_retry"
	RPCCommandAbortRetry                 RPCCommandType = "abort_retry"
	RPCCommandBash                       RPCCommandType = "bash"
	RPCCommandAbortBash                  RPCCommandType = "abort_bash"
	RPCCommandGetSessionStats            RPCCommandType = "get_session_stats"
	RPCCommandExportHtml                 RPCCommandType = "export_html"
	RPCCommandSwitchSession              RPCCommandType = "switch_session"
	RPCCommandFork                       RPCCommandType = "fork"
	RPCCommandClone                      RPCCommandType = "clone"
	RPCCommandGetForkMessages            RPCCommandType = "get_fork_messages"
	RPCCommandGetEntries                 RPCCommandType = "get_entries"
	RPCCommandGetTree                    RPCCommandType = "get_tree"
	RPCCommandGetLastAssistantText       RPCCommandType = "get_last_assistant_text"
	RPCCommandSetSessionName             RPCCommandType = "set_session_name"
	RPCCommandGetMessages                RPCCommandType = "get_messages"
	RPCCommandGetCommands                RPCCommandType = "get_commands"
)

The command names of rpc-types.ts RpcCommand, in its declaration order.

type RPCCompactCommand

type RPCCompactCommand struct {
	ID                 rpcRequestID `json:"id,omitempty"`
	Type               string       `json:"type"`
	CustomInstructions string       `json:"customInstructions,omitempty"`
}

RPCCompactCommand triggers manual compaction. Upstream: rpc-types.ts { type: "compact"; customInstructions?: string }

type RPCCompactionResult

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

type RPCCycleModelCommand

type RPCCycleModelCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

type RPCCycleThinkingLevelCommand

type RPCCycleThinkingLevelCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCCycleThinkingLevelCommand is rpc-types.ts { id?: string; type: "cycle_thinking_level" }.

type RPCEntryAppendedEntry

type RPCEntryAppendedEntry struct {
	Type       string  `json:"type"`
	CustomType string  `json:"customType"`
	Data       any     `json:"data,omitempty"`
	ID         string  `json:"id"`
	ParentID   *string `json:"parentId"`
	Timestamp  string  `json:"timestamp"`
}

RPCEntryAppendedEntry keeps the property order produced by Pi's appendCustomEntry object construction.

type RPCEntryAppendedEvent

type RPCEntryAppendedEvent struct {
	Type  string                `json:"type"`
	Entry RPCEntryAppendedEntry `json:"entry"`
}

RPCEntryAppendedEvent reports an extension-defined Session entry immediately after it is persisted.

type RPCErrorEvent

type RPCErrorEvent struct {
	Type    string `json:"type"` // "error"
	Message string `json:"message"`
}

RPCErrorEvent signals an error that is not tied to a specific command. Upstream: rpc-types.ts error response variant.

type RPCExportHTMLCommand

type RPCExportHTMLCommand struct {
	ID         rpcRequestID `json:"id,omitempty"`
	Type       string       `json:"type"`
	OutputPath string       `json:"outputPath,omitempty"`
}

type RPCExtensionErrorEvent

type RPCExtensionErrorEvent struct {
	Type          string `json:"type"` // "extension_error"
	ExtensionPath string `json:"extensionPath"`
	Event         string `json:"event"`
	Error         string `json:"error"`
}

RPCExtensionErrorEvent reports an extension error from the runner's error listener. Mirrors the object upstream rpc-mode.ts outputs from onError; the stack is not part of it.

type RPCExtensionUIResponse

type RPCExtensionUIResponse struct {
	ID        string `json:"id"`
	Type      string `json:"type"`
	Value     string `json:"value,omitempty"`
	Confirmed bool   `json:"confirmed,omitempty"`
	Cancelled bool   `json:"cancelled,omitempty"`
}

type RPCFollowUpCommand

type RPCFollowUpCommand struct {
	ID      rpcRequestID      `json:"id,omitempty"`
	Type    string            `json:"type"`
	Message string            `json:"message"`
	Images  []RPCImageContent `json:"images,omitempty"`
}

RPCFollowUpCommand queues a message after the active turn settles.

type RPCForkCommand

type RPCForkCommand struct {
	ID      rpcRequestID `json:"id,omitempty"`
	Type    string       `json:"type"`
	EntryID string       `json:"entryId"`
}

type RPCForkResult

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

type RPCGetAvailableModelsCommand

type RPCGetAvailableModelsCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetAvailableModelsCommand is rpc-types.ts { id?: string; type: "get_available_models" }.

type RPCGetAvailableThinkingLevelsCommand

type RPCGetAvailableThinkingLevelsCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

type RPCGetCommandsCommand

type RPCGetCommandsCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetCommandsCommand returns extension, prompt, and skill commands that are invokable through the RPC prompt path.

type RPCGetCommandsData

type RPCGetCommandsData struct {
	Commands []RPCSlashCommand `json:"commands"`
}

type RPCGetEntriesCommand

type RPCGetEntriesCommand struct {
	ID    rpcRequestID `json:"id,omitempty"`
	Type  string       `json:"type"`
	Since string       `json:"since,omitempty"`
}

RPCGetEntriesCommand returns session entries, optionally after the supplied id. Upstream: rpc-types.ts { type: "get_entries"; since?: string }

type RPCGetExtensionsData

type RPCGetExtensionsData struct {
	Paths []string `json:"paths"`
}

RPCGetExtensionsData lists the resolved paths of the loaded extensions in load order, hidden ones included.

type RPCGetForkMessagesCommand

type RPCGetForkMessagesCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetForkMessagesCommand is rpc-types.ts { id?: string; type: "get_fork_messages" }.

type RPCGetLastAssistantTextCommand

type RPCGetLastAssistantTextCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetLastAssistantTextCommand is rpc-types.ts { id?: string; type: "get_last_assistant_text" }.

type RPCGetMessagesCommand

type RPCGetMessagesCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetMessagesCommand is rpc-types.ts { id?: string; type: "get_messages" }.

type RPCGetSessionStatsCommand

type RPCGetSessionStatsCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetSessionStatsCommand is rpc-types.ts { id?: string; type: "get_session_stats" }.

type RPCGetStateCommand

type RPCGetStateCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetStateCommand returns current session state. Upstream: rpc-types.ts:31 { type: "get_state" }

type RPCGetTreeCommand

type RPCGetTreeCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
}

RPCGetTreeCommand is rpc-types.ts { id?: string; type: "get_tree" }.

type RPCImageContent

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

RPCPromptCommand sends a message to the agent. Upstream: rpc-types.ts:25 { type: "prompt"; message: string }

type RPCMessageEndEvent

type RPCMessageEndEvent struct {
	Type string `json:"type"` // "message_end"
	Text string `json:"text"` // full accumulated text
}

RPCMessageEndEvent signals the end of an LLM response turn. Upstream: rpc-types.ts mirrors MessageEndEvent.

type RPCMessageStartEvent

type RPCMessageStartEvent struct {
	Type string `json:"type"` // "message_start"
}

RPCMessageStartEvent is the legacy simplified event shape. RPC mode now forwards upstream-compatible AgentSessionEvent objects via rpcAgentEvent; this type remains only for older unit tests and callers that imported the concrete Go struct from package main.

type RPCModel

type RPCModel struct {
	// Type is Model.type: absent for a model that does not set it (chat is the default).
	Type             ai.ModelType        `json:"type,omitempty"`
	ID               string              `json:"id"`
	Name             string              `json:"name"`
	API              ai.API              `json:"api"`
	Provider         string              `json:"provider"`
	BaseURL          string              `json:"baseUrl"`
	Reasoning        bool                `json:"reasoning"`
	ThinkingLevelMap ai.ThinkingLevelMap `json:"thinkingLevelMap,omitempty"`
	Input            []string            `json:"input"`
	Cost             RPCModelCost        `json:"cost"`
	PromptCache      ai.ModelPromptCache `json:"promptCache,omitempty"`
	ContextWindow    int                 `json:"contextWindow"`
	MaxTokens        int                 `json:"maxTokens"`
	SamplingParams   map[string]any      `json:"samplingParams,omitempty"`
	// SamplingParamsByThinkingLevel is Model.samplingParamsByThinkingLevel.
	SamplingParamsByThinkingLevel ai.SamplingParamsByThinkingLevel `json:"samplingParamsByThinkingLevel,omitempty"`
	Headers                       map[string]string                `json:"headers,omitempty"`
	Compat                        *ai.ModelCompat                  `json:"compat,omitempty"`
	InputLimits                   *ai.ModelInputLimits             `json:"inputLimits,omitempty"`
	// contains filtered or unexported fields
}

func (*RPCModel) MarshalJSON

func (m *RPCModel) MarshalJSON() ([]byte, error)

MarshalJSON writes the model object Pi sends. A model that came from a catalog record (the built-in catalog or a models store) is Pi's catalog object itself, so it keeps that record's member order and spelling; any other model is written member by member.

type RPCModelCost

type RPCModelCost struct {
	Input      float64            `json:"input"`
	Output     float64            `json:"output"`
	CacheRead  float64            `json:"cacheRead"`
	CacheWrite float64            `json:"cacheWrite"`
	Tiers      []RPCModelCostTier `json:"tiers,omitzero"`
}

RPCModelCost is a model's cost; a nil Tiers is a cost with no tiers member and an empty one a cost with tiers: [].

type RPCModelCostTier

type RPCModelCostTier struct {
	InputTokensAbove float64 `json:"inputTokensAbove"`
	Input            float64 `json:"input"`
	Output           float64 `json:"output"`
	CacheRead        float64 `json:"cacheRead"`
	CacheWrite       float64 `json:"cacheWrite"`
}

type RPCModelCycleResult

type RPCModelCycleResult struct {
	Model         *RPCModel             `json:"model"`
	ThinkingLevel ai.ModelThinkingLevel `json:"thinkingLevel"`
	IsScoped      bool                  `json:"isScoped"`
}

type RPCNewSessionCommand

type RPCNewSessionCommand struct {
	ID            rpcRequestID `json:"id,omitempty"`
	Type          string       `json:"type"`
	ParentSession string       `json:"parentSession,omitempty"`
}

type RPCPromptCommand

type RPCPromptCommand struct {
	ID                rpcRequestID      `json:"id,omitempty"`
	Type              string            `json:"type"`
	Message           string            `json:"message"`
	Images            []RPCImageContent `json:"images,omitempty"`
	StreamingBehavior string            `json:"streamingBehavior,omitempty"`
}

type RPCQueueUpdateEvent

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

type RPCResponse

type RPCResponse struct {
	ID      rpcRequestID `json:"id,omitempty"`
	Type    string       `json:"type"`    // always "response"
	Command string       `json:"command"` // mirrors the command type
	Success bool         `json:"success"`
	Data    any          `json:"data,omitempty"`
	Error   string       `json:"error,omitempty"`
}

RPCResponse wraps a command acknowledgement and preserves the request ID's presence. Upstream: rpc-types.ts:110 { type: "response"; command: ...; success: bool; data? }

type RPCSessionInfoChangedEvent

type RPCSessionInfoChangedEvent struct {
	Type string `json:"type"`
	Name string `json:"name,omitempty"`
}

RPCSessionInfoChangedEvent reports the effective Session name. Name is omitted when an extension clears the name with an empty value.

type RPCSessionState

type RPCSessionState struct {
	Model                 *RPCModel             `json:"model"`
	ThinkingLevel         ai.ModelThinkingLevel `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 is the payload for a get_state response.

type RPCSetAutoCompactionCommand

type RPCSetAutoCompactionCommand struct {
	ID      rpcRequestID `json:"id,omitempty"`
	Type    string       `json:"type"`
	Enabled bool         `json:"enabled"`
}

RPCSetAutoCompactionCommand enables/disables auto-compaction. Upstream: rpc-types.ts { type: "set_auto_compaction"; enabled: boolean }

type RPCSetAutoRetryCommand

type RPCSetAutoRetryCommand struct {
	ID      rpcRequestID `json:"id,omitempty"`
	Type    string       `json:"type"`
	Enabled bool         `json:"enabled"`
}

RPCSetAutoRetryCommand enables/disables auto-retry. Upstream: rpc-types.ts { type: "set_auto_retry"; enabled: boolean }

type RPCSetFollowUpModeCommand

type RPCSetFollowUpModeCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
	Mode string       `json:"mode"`
}

RPCSetFollowUpModeCommand sets the follow-up queue mode.

type RPCSetModelCommand

type RPCSetModelCommand struct {
	ID       rpcRequestID `json:"id,omitempty"`
	Type     string       `json:"type"`
	Provider string       `json:"provider"`
	ModelID  string       `json:"modelId"`
}

RPCSetModelCommand changes the active model. Upstream: rpc-types.ts { type: "set_model"; provider: string; modelId: string }

type RPCSetSessionNameCommand

type RPCSetSessionNameCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
	Name string       `json:"name"`
}

RPCSetSessionNameCommand sets the current session name. Upstream: rpc-types.ts { type: "set_session_name"; name: string }

type RPCSetSteeringModeCommand

type RPCSetSteeringModeCommand struct {
	ID   rpcRequestID `json:"id,omitempty"`
	Type string       `json:"type"`
	Mode string       `json:"mode"`
}

RPCSetSteeringModeCommand sets the steering queue mode.

type RPCSetThinkingLevelCommand

type RPCSetThinkingLevelCommand struct {
	ID    rpcRequestID `json:"id,omitempty"`
	Type  string       `json:"type"`
	Level string       `json:"level"` // "off"|"minimal"|"low"|"medium"|"high"|"xhigh"|"max"
}

RPCSetThinkingLevelCommand changes the thinking level. Upstream: rpc-types.ts { type: "set_thinking_level"; level: ThinkingLevel }

type RPCSlashCommand

type RPCSlashCommand = codingagent.SlashCommandInfo

RPCSlashCommand is upstream's RpcSlashCommand (SlashCommandInfo).

type RPCSourceInfo

type RPCSourceInfo = codingagent.PiSourceInfo

RPCSourceInfo is upstream's SourceInfo on the RPC wire; extensions receive the same shape.

type RPCSteerCommand

type RPCSteerCommand struct {
	ID      rpcRequestID      `json:"id,omitempty"`
	Type    string            `json:"type"`
	Message string            `json:"message"`
	Images  []RPCImageContent `json:"images,omitempty"`
}

RPCSteerCommand queues a steering message for the active agent turn.

type RPCSwitchSessionCommand

type RPCSwitchSessionCommand struct {
	ID          rpcRequestID `json:"id,omitempty"`
	Type        string       `json:"type"`
	SessionPath string       `json:"sessionPath"`
}

type RPCTextDeltaEvent

type RPCTextDeltaEvent struct {
	Type    string `json:"type"`    // "text_delta"
	Content string `json:"content"` // incremental text
}

RPCTextDeltaEvent carries an incremental text chunk. Upstream: rpc-types.ts mirrors MessageUpdateEvent text delta.

type RPCThinkingLevelChangedEvent

type RPCThinkingLevelChangedEvent struct {
	Type  string                `json:"type"`
	Level ai.ModelThinkingLevel `json:"level"`
}

type RPCToolResultEvent

type RPCToolResultEvent struct {
	Type    string `json:"type"` // "tool_result"
	Name    string `json:"name"`
	Content string `json:"content"`
	IsError bool   `json:"isError"`
}

RPCToolResultEvent signals a tool call result. Upstream: rpc-types.ts mirrors ToolExecutionEndEvent.

type RPCToolUseEvent

type RPCToolUseEvent struct {
	Type string `json:"type"` // "tool_use"
	Name string `json:"name"`
	Args any    `json:"args"`
}

RPCToolUseEvent signals a tool call by the LLM. Upstream: rpc-types.ts mirrors ToolExecutionStartEvent.

type RPCUIMethod

type RPCUIMethod string

RPCUIMethod is the "method" member of an RpcExtensionUIRequest: the closed union in rpc-types.ts RpcExtensionUIRequest.

const (
	RPCUIMethodSelect        RPCUIMethod = "select"
	RPCUIMethodConfirm       RPCUIMethod = "confirm"
	RPCUIMethodInput         RPCUIMethod = "input"
	RPCUIMethodEditor        RPCUIMethod = "editor"
	RPCUIMethodNotify        RPCUIMethod = "notify"
	RPCUIMethodSetStatus     RPCUIMethod = "setStatus"
	RPCUIMethodSetWidget     RPCUIMethod = "setWidget"
	RPCUIMethodSetTitle      RPCUIMethod = "setTitle"
	RPCUIMethodSetEditorText RPCUIMethod = "set_editor_text"
)

The request methods of rpc-types.ts RpcExtensionUIRequest.

type RPCUsage

type RPCUsage struct {
	Input        int          `json:"input"`
	Output       int          `json:"output"`
	CacheRead    int          `json:"cacheRead"`
	CacheWrite   int          `json:"cacheWrite"`
	CacheWrite1h *int         `json:"cacheWrite1h,omitempty"`
	Reasoning    *int         `json:"reasoning,omitempty"`
	TotalTokens  int          `json:"totalTokens"`
	Cost         ai.UsageCost `json:"cost"`
	// contains filtered or unexported fields
}

RPCUsage is a Usage snapshot in the member order of the provider code that builds it (MarshalJSON).

func (RPCUsage) AppendStringify

func (u RPCUsage) AppendStringify(dst []byte) ([]byte, error)

AppendStringify appends the JSON.stringify text of MarshalJSON's output to dst (json.StringifyAppender).

func (RPCUsage) MarshalJSON

func (u RPCUsage) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in the order Pi's providers create them. The OpenAI and Google providers build usage as one literal with reasoning before totalTokens (openai-completions.ts:1549-1557, openai-responses-shared.ts:566-574, google-generative-ai.ts:233-249). The Anthropic and Bedrock providers build input, output, cacheRead, cacheWrite, totalTokens and cost, then assign cacheWrite1h and, for Anthropic, reasoning (anthropic-messages.ts:589-596, :684, :851; bedrock-converse-stream.ts:143-150, :715). Only those two providers report cacheWrite1h, so its presence selects the appended order.

type ResolveCliModelResult

type ResolveCliModelResult = codingagent.ResolveCliModelResult

ResolveCliModelResult is the shared model-selection result used by CLI and auth commands.

func ResolveCliModel

func ResolveCliModel(cliProvider, cliModel, cliThinking string, inlineAPIKey bool, runtime codingagent.ModelResolverRuntime) ResolveCliModelResult

ResolveCliModel delegates CLI and auth model selection to the shared resolver.

type ScopedModel

type ScopedModel = codingagent.ScopedModel

ScopedModel is the shared scope entry used by startup and interactive selection.

Source Files

Jump to

Keyboard shortcuts

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