Documentation
¶
Overview ¶
Model picker auth-filter scope toggle.
AuthenticatedProviders + ReachableProviders are the single source of truth for "which providers can the user actually talk to right now" vs "which providers does coding.BuildModel even know how to wire".
Used by interactive `/model` overlay to default the picker scope to {auth ∩ reachable} and clamp the all-scope view to {reachable} (the other ~19 catalog providers would mis-route through BuildModel's OpenAI-compatible default branch and silently fail at first token).
Mirrors upstream pi-coding-agent's `model-selector.ts::scopedModels` filter logic: pig computes the scoped set here at picker-open time rather than carrying it on SettingsManager.
bash_executor.go: type aliases and shim for the !cmd interactive path.
User bash execution lives in internal/codingagent/tools/bash_executor.go (upstream core/bash-executor.ts executeBashWithOperations). This file re-exports its types so interactive code can call it without qualifying the tools sub-package.
extensions.go defines extension event names and the TUI-backed UI surface:
- Event name constants
- ToolCallEventResult (agent loop hook)
- ExtensionUIContext interface + NoopUI (headless fallback)
- ExtensionContext (shared mutable state for the agent loop)
- SlashCommand type (used by slash_commands.go)
- TUIUIContext (interactive mode UI)
Index ¶
- Constants
- Variables
- func AgentActivityOutcome(messages []agent.AgentMessage, runErr error) extension.AgentActivityOutcome
- func AgentDir() string
- func AgentLoopEventType(ev agent.AgentEvent) string
- func AuthenticatedProviders(agentDir string) map[string]bool
- func BugReportArchiveFileName(id string) string
- func BugReportIssueLink(metadata BugReportMetadata, archiveName, upstreamVersion string) string
- func CanonicalizePath(path string) string
- func CatalogRoot(agentDir string) string
- func CleanupWindowsSelfUpdateQuarantine(packageDir string)
- func ClearCrashLog(path string)
- func CompareChangelogEntries(a, b ChangelogEntry) int
- func CompareVersions(a, b string) int
- func ConfigRoot() string
- func ContainerRemediation(exePath string) string
- func ConvertImageBytesToPng(data []byte) []byte
- func ConvertToPng(base64Data, mimeType string) *tui.ConvertedImage
- func CrashLogPath(agentDir string) string
- func CreateShareTrailingEntries(state ShareState, parentID *string, timestamp string) []any
- func CurrentSystemMessage(messages []agent.AgentMessage) *ai.SystemMessage
- func DefaultAgentDir() string
- func DefaultSkillsDir() string
- func DetectSupportedImageMimeType(data []byte) string
- func DispatchAgentLoopEvent(runner *inproc.Runner, ev agent.AgentEvent, ...)
- func ExpandPromptTemplate(line string, templates []PromptTemplate) (string, bool)
- func ExpandSkillCommand(text string, skills []*SkillDef) (string, bool)
- func ExpandTildePath(path string) string
- func ExportSessionForShare(filePath string, session *Session, state ShareState) (string, error)
- func ExportSessionToJsonl(session *Session, outputPath string, createTrailingEntries TrailingEntries) (string, error)
- func ExtensionForImageMIME(mime string) string
- func ExtensionsInLoadOrder(configured, builtins []extension.Extension) []extension.Extension
- func FindExtensionStackMatches(stack string, extensions []ExtensionStackMetadata) []string
- func FormatCacheWarmingStatus(status CacheWarmingStatus, now int64) string
- func FormatCacheWarmingUsage(entry UsageEntry) string
- func FormatChangelogForChat(entries []ChangelogEntry) string
- func FormatCrashExtensionHint(extensionMatches []string) string
- func FormatNoAPIKeyFoundMessage(provider string) string
- func FormatNoModelSelectedMessage() string
- func FormatNoModelsAvailableMessage() string
- func FormatPathRelativeToCwdOrAbsolute(filePath, cwd string) string
- func GenerateEntryID() (string, error)
- func GenerateSessionID() (string, error)
- func GetCacheWarmingDelayMs(ttlMs int64) (int64, bool)
- func GetCwdRelativePath(filePath, cwd string) string
- func GetPackageDir() string
- func GetProjectTrustParentPath(cwd string) string
- func GetProjectTrustPath(cwd string) string
- func GetPromptCacheTtlMs(model *ai.Model, options ai.StreamOptions) (int64, bool)
- func GetRadiusGatewayURL() string
- func GetSelfUpdateUnavailableInstruction(_ string, _ []string, _ ...string) string
- func GetUpdateInstruction(packageName string, npmCommand []string) string
- func GitInstallRoot(cwd, agentDir string, project bool) string
- func HasTrustRequiringProjectResources(cwd string) bool
- func ImmutableBinaryRemediation(exePath string) string
- func IsContextOverflow(msg *agent.AssistantMessage, contextWindow int) bool
- func IsRecoverableLength(msg *agent.AssistantMessage, desiredMaxOutput int) bool
- func IsReplayable(model *ai.Model, options ai.StreamOptions) bool
- func IsRetryableError(msg *agent.AssistantMessage, contextWindow int) bool
- func IsStdoutTakenOver() bool
- func IsWSL(getenv func(string) string, readFile func(string) ([]byte, error)) bool
- func KeybindingsFile(agentDir string) string
- func ListSkills(skillsDir string) ([]string, error)
- func MarkPathIgnoredByCloudSync(path string)
- func ModelNetworkEnabled() bool
- func NPMInstallRoot(cwd, agentDir string, project bool) string
- func NormalizePromptContent(content []ai.UserContentBlock, autoResize bool, model *ai.Model) []ai.UserContentBlock
- func NormalizeToolResultImages(result agent.AgentToolResult, autoResize bool) agent.AgentToolResult
- func OpenExternalEditor(ctx context.Context, initial string, configuredEditor string) (string, error)
- func ParsePromptArgs(s string) []string
- func PigletArtifactsDir() string
- func PigletRecordsDir() string
- func PigletsDir() string
- func PlatformKey() string
- func PrepareCLIImageAttachment(data []byte, mime string) ([]byte, string, string, error)
- func PrepareWindowsNpmSelfUpdate(exePath string) error
- func ProjectConfigDir(cwd string) string
- func ProjectStateDir(cwd, namespace string) string
- func ProviderLoginHelp() string
- func QuarantineWindowsNativeDependencies(packageDir string) error
- func RFC3339NowNano() string
- func RawStdoutWriter() io.Writer
- func ReachableProviders() map[string]bool
- func ReadClipboardImage() ([]byte, string, error)
- func ReadClipboardImageContext(parent context.Context) ([]byte, string, error)
- func RedactBugReportJSON(value any) (any, error)
- func RedactBugReportURL(value string) string
- func RenderLoginHeader(definition extension.ValidatedLoginDefinition, width int, ...) []string
- func RenderTreeASCII(root *SessionTreeNode) string
- func ReportDiagnostics(diagnostics []AgentSessionRuntimeDiagnostic)
- func RestoreStdout()
- func RunAgentBeforeSettle(ctx context.Context, session *Session, a *agent.Agent, runner *inproc.Runner, ...) (bool, error)
- func RunInputHandlers(ctx context.Context, runner *inproc.Runner, text string, ...) (string, []ai.ImageContent, bool, error)
- func RunMigrations(cwd, agentDir string) (migratedAuthProviders []string, deprecationWarnings []string, err error)
- func RunPackageManagerUpdate(cmd *SelfUpdateCommand) error
- func SaveClipboardImageToTempFile(bytes []byte, mime string) (string, error)
- func SelectStartupSession(currentLoader func() ([]SessionInfo, error), ...) (path string, selected bool, err error)
- func SelfReplace(ctx context.Context, client *http.Client, bin UpdateBinary) error
- func SelfReplaceAt(ctx context.Context, client *http.Client, bin UpdateBinary, exePath string) error
- func SelfReplaceAtWithCommit(ctx context.Context, client *http.Client, bin UpdateBinary, exePath string, ...) error
- func SelfUpdateFallback() string
- func SerializeSessionBranch(header SessionHeader, branch []SessionEntry, now time.Time, ...) (string, error)
- func SessionEntryToContextMessages(entry SessionEntry) []agent.AgentMessage
- func ShowStartupInput(title, placeholder string, opts StartupUIOptions) (value string, selected bool, err error)
- func ShowStartupSelector(title string, options []string, opts StartupUIOptions) (index int, selected bool, err error)
- func SkillDiagnostics(skill *SkillDef) []string
- func StartupKeybindHints(km *KeybindingsManager) string
- func StateDir(namespace string) string
- func SubstitutePromptArgs(content string, args []string) string
- func SystemMessageFromAgentMessage(message agent.AgentMessage) (ai.SystemMessage, bool)
- func TakeOverStdout() error
- func ToolResultEventContent(result agent.AgentToolResult) []any
- func ToolResultEventOverride(result *extension.ToolResultEventResult) agent.AfterToolCallResult
- func UnsupportedRemediation(exePath string) string
- func UpdateSourceURL() string
- func WireModelOperations(bridge ModelOperationBridge, bindings ModelOperationBindings) func()
- func WriteBugReportArchive(bundle BugReportBundle, path string) (err error)
- func WriteRawStdout(text string) (int, error)
- func WriteStandaloneReceipt(exe, version, source string) error
- type AgentSessionRuntimeDiagnostic
- type BashExecOptions
- type BashExecutionEntry
- type BashExecutionMessage
- type BashResult
- type BinaryUpdate
- type BranchSummaryConfig
- type BranchSummaryEntry
- type BugReportAssistantDiagnostic
- type BugReportAuthStatus
- type BugReportBundle
- type BugReportDiagnostics
- type BugReportEnvironment
- type BugReportExtension
- type BugReportExtensionError
- type BugReportFile
- type BugReportInputs
- type BugReportMetadata
- type BugReportModel
- type BugReportOptions
- type BugReportProvider
- type BugReportSessionEntryData
- type BugReportSessionInfo
- type BugReportSettings
- type BugReportTerminalEnv
- type BuiltinSlashCommand
- type CacheWarmRequest
- type CacheWarmer
- func (w *CacheWarmer) Cancel()
- func (w *CacheWarmer) Close()
- func (w *CacheWarmer) OnAgentSettled()
- func (w *CacheWarmer) OnModeChanged()
- func (w *CacheWarmer) SetOnWarmed(onWarmed func(context.Context, UsageEntry))
- func (w *CacheWarmer) Start(request CacheWarmRequest, isCurrent func() bool)
- func (w *CacheWarmer) Status() CacheWarmingStatus
- func (w *CacheWarmer) Wait()
- type CacheWarmerSessionManager
- type CacheWarmingAction
- type CacheWarmingDecide
- type CacheWarmingDecision
- type CacheWarmingDecisionEvent
- type CacheWarmingMode
- type CacheWarmingStatus
- type CatalogRefreshOptions
- type CatalogRefreshResult
- type ChangelogEntry
- type ChatViewport
- type ChatViewportOptions
- type CompactionConfig
- type CompactionEntry
- type CompactionModelOverride
- type CompactionSettingsJSON
- type ContextEditEntry
- type ContextEditReplacement
- type ContextFile
- type CrashInput
- type CrashRecord
- type CustomEntry
- type CustomMessageEntry
- type ExtUIContext
- func (u *ExtUIContext) AddAutocompleteProvider(factory extension.AutocompleteProviderFactory)
- func (u *ExtUIContext) Confirm(ctx context.Context, title, message string, ...) (bool, error)
- func (u *ExtUIContext) Custom(_ context.Context, _ any, _ any) (any, error)
- func (u *ExtUIContext) Editor(ctx context.Context, title, prefill string) (string, error)
- func (u *ExtUIContext) GetAllThemes() []extension.ThemeMeta
- func (u *ExtUIContext) GetEditorComponent() any
- func (u *ExtUIContext) GetEditorText() string
- func (u *ExtUIContext) GetTheme(name string) (extension.Theme, error)
- func (u *ExtUIContext) GetToolsExpanded() bool
- func (u *ExtUIContext) Input(ctx context.Context, title, placeholder string, ...) (string, error)
- func (u *ExtUIContext) Notify(message, kind string)
- func (u *ExtUIContext) OnRemoteTerminalInput(extensionName string, handler extension.RemoteTerminalInputHandler) func()
- func (u *ExtUIContext) OnTerminalInput(handler extension.TerminalInputHandler) func()
- func (u *ExtUIContext) PasteToEditor(text string)
- func (u *ExtUIContext) ReportsDialogInitiation() bool
- func (u *ExtUIContext) RunRemoteOverlay(opts extension.RemoteOverlayOptions, host extension.RemoteOverlayHost, ...) (any, bool)
- func (u *ExtUIContext) Select(ctx context.Context, title string, options []string, ...) (string, error)
- func (u *ExtUIContext) SetEditorComponent(factory any)
- func (u *ExtUIContext) SetEditorText(text string)
- func (u *ExtUIContext) SetFooter(factory any)
- func (u *ExtUIContext) SetHeader(factory any)
- func (u *ExtUIContext) SetHiddenThinkingLabel(label string)
- func (u *ExtUIContext) SetLogin(definition extension.LoginDefinition) error
- func (u *ExtUIContext) SetStatus(key, text string)
- func (u *ExtUIContext) SetTheme(theme any) extension.SetThemeResult
- func (u *ExtUIContext) SetTitle(title string)
- func (u *ExtUIContext) SetToolsExpanded(expanded bool)
- func (u *ExtUIContext) SetWidget(key string, content any, opts extension.ExtensionWidgetOptions)
- func (u *ExtUIContext) SetWorkingIndicator(options extension.WorkingIndicatorOptions)
- func (u *ExtUIContext) SetWorkingMessage(message string)
- func (u *ExtUIContext) SetWorkingVisible(visible bool)
- func (u *ExtUIContext) Theme() extension.Theme
- type ExtensionConflict
- type ExtensionContext
- type ExtensionStackMetadata
- type ExtensionUIContext
- type InteractiveMode
- type InteractiveOptions
- type InteractiveSessionHandle
- type KeyID
- type KeybindingConflict
- type KeybindingDefinition
- type KeybindingsManager
- func (km *KeybindingsManager) Conflicts() []KeybindingConflict
- func (km *KeybindingsManager) DisplayFor(action string) string
- func (km *KeybindingsManager) Get(action string) []KeyID
- func (km *KeybindingsManager) HotkeyLines() []string
- func (km *KeybindingsManager) KeyText(action string) string
- func (km *KeybindingsManager) Matches(input, action string) bool
- func (km *KeybindingsManager) MatchesEditorHistory(input string) bool
- func (km *KeybindingsManager) Reload() error
- func (km *KeybindingsManager) Resolve(input string) string
- func (km *KeybindingsManager) ResolvedBindings() map[string][]string
- func (km *KeybindingsManager) Save(path string) error
- func (km *KeybindingsManager) SetUserBindings(bindings map[string][]KeyID)
- type LabelEntry
- type LoadPromptTemplatesResult
- type LoginHeaderOptions
- type MarkdownSettings
- type MessageEntry
- type ModelChangeEntry
- type ModelEntry
- type ModelMutationOptions
- type ModelOperationBindings
- type ModelOperationBridge
- type ModelRegistry
- func (r *ModelRegistry) AvailableProviderCount() int
- func (r *ModelRegistry) BugReportProviderInfo(providerID string) *BugReportProvider
- func (r *ModelRegistry) GetAll() []ModelEntry
- func (r *ModelRegistry) GetAvailable() []ModelEntry
- func (r *ModelRegistry) GetProviderAuthStatus(providerID string) ai.AuthStatus
- func (r *ModelRegistry) GetProviderDisplayName(providerID string) string
- func (r *ModelRegistry) HasAnyKey(providerID string) bool
- func (r *ModelRegistry) HasConfiguredAuth(providerID string) bool
- func (r *ModelRegistry) HasGeneratedModel(providerID, modelID string) bool
- func (r *ModelRegistry) HasModelDefinition(providerID, modelID string) bool
- func (r *ModelRegistry) LoadError() string
- func (r *ModelRegistry) RadiusAPIKey(ctx context.Context, providerID string) (string, error)
- func (r *ModelRegistry) RadiusOAuth(providerID string) (*ai.RadiusOAuth, bool)
- func (r *ModelRegistry) RadiusOAuthFlows() []*ai.RadiusOAuth
- func (r *ModelRegistry) Refresh()
- func (r *ModelRegistry) RefreshCatalogs(ctx context.Context, options CatalogRefreshOptions) CatalogRefreshResult
- func (r *ModelRegistry) RegisterProvider(name string, configMap extension.ProviderConfig)
- func (r *ModelRegistry) RemoveRuntimeAPIKey(providerID string)
- func (r *ModelRegistry) Resolve(providerID, modelID string) (ModelEntry, bool)
- func (r *ModelRegistry) ResolveGeneratedModel(providerID, modelID string, generated *ai.GeneratedModel) ModelEntry
- func (r *ModelRegistry) RuntimeAPIKey(providerID string) (string, bool)
- func (r *ModelRegistry) RuntimeModels() []RuntimeModel
- func (r *ModelRegistry) SetAuthStorage(auth *ai.AuthStorage)
- func (r *ModelRegistry) SetChangeListener(notify func()) func()
- func (r *ModelRegistry) SetModelsStore(store ai.ModelsStore)
- func (r *ModelRegistry) SetProvider(name string, configMap extension.ProviderConfig)
- func (r *ModelRegistry) SetRuntimeAPIKey(providerID, apiKey string)
- func (r *ModelRegistry) UnregisterProvider(name string)
- type NavigateTreeResult
- type NoopUI
- type PackageManagerOwner
- type PackageSource
- type ParsedSkillBlockFromText
- type ProcessedCLIArgs
- type ProjectTrustOption
- type ProjectTrustStore
- type ProjectTrustStoreEntry
- type ProjectTrustUpdate
- type ProjectedSessionEntry
- type PromptTemplate
- type ProviderRetryConfig
- type ProviderRetrySettings
- type ReloadCellDiag
- type ReloadDiag
- type ReloadResourceSnapshot
- type RequestAuthRuntime
- func (r *RequestAuthRuntime) CheckAuth(ctx context.Context, providerID string) (*ai.AuthCheck, error)
- func (r *RequestAuthRuntime) GetAuth(ctx context.Context, providerID string, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
- func (r *RequestAuthRuntime) GetError() string
- func (r *RequestAuthRuntime) GetModelAuth(ctx context.Context, model RuntimeModel, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
- func (r *RequestAuthRuntime) GetModels(providerID string) []RuntimeModel
- func (r *RequestAuthRuntime) GetProvider(providerID string) *RuntimeProvider
- func (r *RequestAuthRuntime) GetProviders() []*RuntimeProvider
- func (r *RequestAuthRuntime) HasConfiguredAuth(providerID string) bool
- func (r *RequestAuthRuntime) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
- func (r *RequestAuthRuntime) Refresh(ctx context.Context)
- type RequestAuthRuntimeOptions
- type ResolvedPath
- type ResourceSourceInfo
- type RetryConfig
- type RetrySettingsJSON
- type RuntimeModel
- type RuntimeProvider
- type SelfUpdateActionResult
- type SelfUpdateCommand
- type SelfUpdatePackageTarget
- type SelfUpdateProvenance
- type SelfUpdateTier
- type Session
- func (s *Session) Accounting() SessionAccounting
- func (s *Session) AppendBashExecution(command, output string, exitCode *int, cancelled, truncated bool, ...) (string, error)
- func (s *Session) AppendBranchSummary(parentID *string, summary string, details any, fromHook bool, usage *ai.Usage) (string, error)
- func (s *Session) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int, details any, fromHook bool, ...) (string, error)
- func (s *Session) AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
- func (s *Session) AppendCustomMessage(customType string, content any, display bool, details any) (string, error)
- func (s *Session) AppendEntry(entry any) error
- func (s *Session) AppendLabelChange(targetID string, label *string) error
- func (s *Session) AppendMessage(msg agent.AgentMessage) (string, error)
- func (s *Session) AppendModelSwitch(provider, modelID, displayName string) error
- func (s *Session) AppendThinkingLevelChange(level string) error
- func (s *Session) AppendUsage(kind, provider, model string, usage ai.Usage, note string) (UsageEntry, error)
- func (s *Session) Branch(leafID string) []SessionEntry
- func (s *Session) BuildContext(leafID *string) []agent.AgentMessage
- func (s *Session) BuildSessionProjection() SessionProjection
- func (s *Session) CWD() string
- func (s *Session) Entries() []SessionEntry
- func (s *Session) EntryByID(id string) (SessionEntry, bool)
- func (s *Session) FooterUsageTotals() footerUsageTotals
- func (s *Session) Fork(forkFromID string) error
- func (s *Session) GetBranch() []SessionEntry
- func (s *Session) GetSessionName() string
- func (s *Session) Header() SessionHeader
- func (s *Session) ID() string
- func (s *Session) LatestCompactionTimestampMs() (int64, bool)
- func (s *Session) LeafID() *string
- func (s *Session) ParentSession() string
- func (s *Session) Path() string
- func (s *Session) SetLeafID(id *string) error
- func (s *Session) SetPath(p string)
- func (s *Session) Tree() *SessionTreeNode
- func (s *Session) UndecodableCount() int
- type SessionAccounting
- type SessionCacheWaste
- type SessionEntry
- type SessionEntryBase
- type SessionHeader
- type SessionInfo
- type SessionInfoEntry
- type SessionManager
- func (sm *SessionManager) CWD() string
- func (sm *SessionManager) Clone(source *Session, leafID string) (*Session, error)
- func (sm *SessionManager) Create(id, parentSessionPath string) (*Session, error)
- func (sm *SessionManager) Current() *Session
- func (sm *SessionManager) DeleteSession(path string) error
- func (sm *SessionManager) FindByID(id string) string
- func (sm *SessionManager) FindMostRecent() string
- func (sm *SessionManager) FindMostRecentForContinue() string
- func (sm *SessionManager) ForkFromFile(sourcePath string) (*Session, error)
- func (sm *SessionManager) ForkToNewSession(source *Session, userMsgEntryID string) (*Session, string, error)
- func (sm *SessionManager) ListAllSessions() ([]SessionInfo, error)
- func (sm *SessionManager) ListCurrentSessions() ([]SessionInfo, error)
- func (sm *SessionManager) ListSessions() ([]SessionInfo, error)
- func (sm *SessionManager) Load(path string) (*Session, error)
- func (sm *SessionManager) RenameSession(path, newName string) error
- func (sm *SessionManager) SessionDir() string
- type SessionProjection
- type SessionTokenStats
- type SessionTreeNode
- type SessionUsageBreakdown
- type Settings
- func (s Settings) GetAutocompleteMaxVisible() int
- func (s Settings) GetBlockImages() bool
- func (s Settings) GetClearOnShrink() bool
- func (s Settings) GetCodeBlockIndent() string
- func (s Settings) GetCollapseChangelog() bool
- func (s Settings) GetCommandPrefix() string
- func (s Settings) GetEditorPaddingX() int
- func (s Settings) GetHideThinkingBlock() bool
- func (s Settings) GetImageAutoResize() bool
- func (s Settings) GetImageWidthCells() int
- func (s Settings) GetOutputPad() int
- func (s Settings) GetQuietStartup() bool
- func (s Settings) GetShellPath() (string, error)
- func (s Settings) GetShowCacheMissNotices() bool
- func (s Settings) GetShowHardwareCursor() bool
- func (s Settings) GetShowImages() bool
- func (s Settings) GetShowTerminalProgress() bool
- func (s Settings) GetTerminalCapabilityOverrides() tui.CapabilityOverrides
- func (s Settings) MarshalJSON() ([]byte, error)
- func (s *Settings) UnmarshalJSON(data []byte) error
- type SettingsError
- type SettingsManager
- func (sm *SettingsManager) AgentDir() string
- func (sm *SettingsManager) ApplyOverrides(overrides Settings)
- func (sm *SettingsManager) CWD() string
- func (sm *SettingsManager) DrainErrors() []SettingsError
- func (sm *SettingsManager) Flush() error
- func (sm *SettingsManager) Get() Settings
- func (sm *SettingsManager) GetAutocompleteMaxVisible() int
- func (sm *SettingsManager) GetBlockImages() bool
- func (sm *SettingsManager) GetBranchSummarySettings() BranchSummaryConfig
- func (sm *SettingsManager) GetBranchSummarySkipPrompt() bool
- func (sm *SettingsManager) GetCacheWarmingMode() CacheWarmingMode
- func (sm *SettingsManager) GetClearOnShrink() bool
- func (sm *SettingsManager) GetCodeBlockIndent() string
- func (sm *SettingsManager) GetCollapseChangelog() bool
- func (sm *SettingsManager) GetCompactionEnabled() bool
- func (sm *SettingsManager) GetCompactionKeepRecentTokens() int
- func (sm *SettingsManager) GetCompactionReserveTokens() int
- func (sm *SettingsManager) GetCompactionSettings() CompactionConfig
- func (sm *SettingsManager) GetDefaultModel() string
- func (sm *SettingsManager) GetDefaultProjectTrust() string
- func (sm *SettingsManager) GetDefaultProvider() string
- func (sm *SettingsManager) GetDefaultThinkingLevel() string
- func (sm *SettingsManager) GetDefaultTools() []string
- func (sm *SettingsManager) GetDoubleEscapeAction() string
- func (sm *SettingsManager) GetEditorPaddingX() int
- func (sm *SettingsManager) GetEnableAnalytics() bool
- func (sm *SettingsManager) GetEnableInstallTelemetry() bool
- func (sm *SettingsManager) GetEnableSkillCommands() bool
- func (sm *SettingsManager) GetEnabledModels() []string
- func (sm *SettingsManager) GetExtensionPaths() []string
- func (sm *SettingsManager) GetExternalEditorCommand() string
- func (sm *SettingsManager) GetFollowUpMode() string
- func (sm *SettingsManager) GetFullscreenCopyOnSelect() bool
- func (sm *SettingsManager) GetFullscreenExitOutput() string
- func (sm *SettingsManager) GetFullscreenScrollbar() string
- func (sm *SettingsManager) GetGlobalSettings() Settings
- func (sm *SettingsManager) GetHideThinkingBlock() bool
- func (sm *SettingsManager) GetHttpIdleTimeoutMs() (int, error)
- func (sm *SettingsManager) GetImageAutoResize() bool
- func (sm *SettingsManager) GetImageWidthCells() int
- func (sm *SettingsManager) GetLastChangelogVersion() string
- func (sm *SettingsManager) GetMermaidRenderingMode() string
- func (sm *SettingsManager) GetModelCompactionSettings(provider, modelID string) CompactionConfig
- func (sm *SettingsManager) GetModelThinkingLevel(provider, modelID string) string
- func (sm *SettingsManager) GetNpmCommand() []string
- func (sm *SettingsManager) GetOutputPad() int
- func (sm *SettingsManager) GetPackages() []PackageSource
- func (sm *SettingsManager) GetProjectSettings() Settings
- func (sm *SettingsManager) GetPromptTemplatePaths() []string
- func (sm *SettingsManager) GetProviderRequestTimeoutMs() (int, error)
- func (sm *SettingsManager) GetProviderRetrySettings() ProviderRetryConfig
- func (sm *SettingsManager) GetQuietStartup() bool
- func (sm *SettingsManager) GetRetryEnabled() bool
- func (sm *SettingsManager) GetRetrySettings() RetryConfig
- func (sm *SettingsManager) GetSessionDir() (string, error)
- func (sm *SettingsManager) GetShellCommandPrefix() string
- func (sm *SettingsManager) GetShellPath() (string, error)
- func (sm *SettingsManager) GetShowCacheMissNotices() bool
- func (sm *SettingsManager) GetShowHardwareCursor() bool
- func (sm *SettingsManager) GetShowImages() bool
- func (sm *SettingsManager) GetShowTerminalProgress() bool
- func (sm *SettingsManager) GetSkillPaths() []string
- func (sm *SettingsManager) GetSteeringMode() string
- func (sm *SettingsManager) GetTerminalCapabilityOverrides() tui.CapabilityOverrides
- func (sm *SettingsManager) GetTheme() string
- func (sm *SettingsManager) GetThemePaths() []string
- func (sm *SettingsManager) GetThinkingBudgets() *ThinkingBudgetsSettings
- func (sm *SettingsManager) GetTrackingID() string
- func (sm *SettingsManager) GetTransport() string
- func (sm *SettingsManager) GetTreeFilterMode() string
- func (sm *SettingsManager) GetTuiMode() string
- func (sm *SettingsManager) GetWarnings() WarningSettings
- func (sm *SettingsManager) GlobalPath() string
- func (sm *SettingsManager) GlobalSettingsPath() string
- func (sm *SettingsManager) IsInstallTelemetryEnabled() bool
- func (sm *SettingsManager) IsProjectTrusted() bool
- func (sm *SettingsManager) Load()
- func (sm *SettingsManager) Reload()
- func (sm *SettingsManager) RemoveModelThinkingLevel(provider, modelID string) error
- func (sm *SettingsManager) SetAutocompleteMaxVisible(n int) error
- func (sm *SettingsManager) SetBlockImages(blocked bool) error
- func (sm *SettingsManager) SetCacheWarmingMode(mode CacheWarmingMode) error
- func (sm *SettingsManager) SetClearOnShrink(enabled bool) error
- func (sm *SettingsManager) SetCollapseChangelog(collapse bool) error
- func (sm *SettingsManager) SetCompactionEnabled(enabled bool) error
- func (sm *SettingsManager) SetDefaultModel(m string) error
- func (sm *SettingsManager) SetDefaultModelAndProvider(provider, model string) error
- func (sm *SettingsManager) SetDefaultProvider(p string) error
- func (sm *SettingsManager) SetDefaultThinkingLevel(level string) error
- func (sm *SettingsManager) SetDoubleEscapeAction(action string) error
- func (sm *SettingsManager) SetEditorPaddingX(padding int) error
- func (sm *SettingsManager) SetEnableAnalytics(enabled bool) error
- func (sm *SettingsManager) SetEnableInstallTelemetry(enabled bool) error
- func (sm *SettingsManager) SetEnableSkillCommands(enabled bool) error
- func (sm *SettingsManager) SetEnabledModels(patterns []string) error
- func (sm *SettingsManager) SetExtensionPaths(paths []string) error
- func (sm *SettingsManager) SetFollowUpMode(mode string) error
- func (sm *SettingsManager) SetFullscreenCopyOnSelect(enabled bool) error
- func (sm *SettingsManager) SetFullscreenExitOutput(output string) error
- func (sm *SettingsManager) SetFullscreenScrollbar(mode string) error
- func (sm *SettingsManager) SetHideThinkingBlock(hide bool) error
- func (sm *SettingsManager) SetHttpIdleTimeoutMs(timeoutMs float64) error
- func (sm *SettingsManager) SetImageAutoResize(enabled bool) error
- func (sm *SettingsManager) SetImageWidthCells(width int) error
- func (sm *SettingsManager) SetLastChangelogVersion(version string) error
- func (sm *SettingsManager) SetMermaidRenderingMode(mode string) error
- func (sm *SettingsManager) SetModelThinkingLevel(provider, modelID, level string) error
- func (sm *SettingsManager) SetNpmCommand(cmd []string) error
- func (sm *SettingsManager) SetOutputPad(padding int) error
- func (sm *SettingsManager) SetPackages(pkgs []PackageSource) error
- func (sm *SettingsManager) SetProjectExtensionPaths(paths []string) error
- func (sm *SettingsManager) SetProjectPackages(pkgs []PackageSource) error
- func (sm *SettingsManager) SetProjectPromptTemplatePaths(paths []string) error
- func (sm *SettingsManager) SetProjectSkillPaths(paths []string) error
- func (sm *SettingsManager) SetProjectThemePaths(paths []string) error
- func (sm *SettingsManager) SetProjectTrusted(trusted bool)
- func (sm *SettingsManager) SetPromptTemplatePaths(paths []string) error
- func (sm *SettingsManager) SetQuietStartup(quiet bool) error
- func (sm *SettingsManager) SetRetryEnabled(enabled bool) error
- func (sm *SettingsManager) SetShellCommandPrefix(prefix string) error
- func (sm *SettingsManager) SetShellPath(path string) error
- func (sm *SettingsManager) SetShowCacheMissNotices(show bool) error
- func (sm *SettingsManager) SetShowHardwareCursor(enabled bool) error
- func (sm *SettingsManager) SetShowImages(show bool) error
- func (sm *SettingsManager) SetShowTerminalProgress(enabled bool) error
- func (sm *SettingsManager) SetSkillPaths(paths []string) error
- func (sm *SettingsManager) SetSteeringMode(mode string) error
- func (sm *SettingsManager) SetTheme(theme string) error
- func (sm *SettingsManager) SetThemePaths(paths []string) error
- func (sm *SettingsManager) SetTransport(transport string) error
- func (sm *SettingsManager) SetTreeFilterMode(mode string) error
- func (sm *SettingsManager) SetTuiMode(mode string) error
- func (sm *SettingsManager) SetWarnings(warnings WarningSettings) error
- func (sm *SettingsManager) UpdateGlobal(fn func(*Settings)) error
- func (sm *SettingsManager) UpdateProject(fn func(*Settings)) error
- type ShareState
- type ShareTool
- type SkillDef
- type SlashCommand
- type SlashCommandInfo
- type SlashCommandSource
- type SlashContext
- type SlashHandler
- type SlashRegistry
- func (r *SlashRegistry) All() []SlashCommandInfo
- func (r *SlashRegistry) Dispatch(sc *SlashContext, line string, extCtx *ExtensionContext) error
- func (r *SlashRegistry) Register(cmd BuiltinSlashCommand)
- func (r *SlashRegistry) ReplaceDynamic(cmds []SlashCommand)
- func (r *SlashRegistry) Resolve(name string) (string, bool)
- type StandaloneReceipt
- type StartupUIOptions
- type StatusLine
- func (s *StatusLine) Flash(msg string, ttl time.Duration)
- func (s *StatusLine) GetExtensionStatuses() map[string]string
- func (s *StatusLine) GetHiddenThinkingLabel() string
- func (s *StatusLine) GetWorkingMessage() string
- func (s *StatusLine) GitBranch() string
- func (s *StatusLine) OnBranchChange(fn func()) func()
- func (s *StatusLine) ProviderCount() int
- func (s *StatusLine) Render(width int) []string
- func (s *StatusLine) ResetContextUsage()
- func (s *StatusLine) SetAgentName(name string)
- func (s *StatusLine) SetAutoCompactEnabled(enabled bool)
- func (s *StatusLine) SetContextUsage(tokens *int, contextWindow int)
- func (s *StatusLine) SetCwd(cwd string)
- func (s *StatusLine) SetExtensionStatus(key, text string)
- func (s *StatusLine) SetHiddenThinkingLabel(label string)
- func (s *StatusLine) SetModel(m *ai.Model)
- func (s *StatusLine) SetName(name string)
- func (s *StatusLine) SetProviderCount(n int)
- func (s *StatusLine) SetStatusHook(fn func(string))
- func (s *StatusLine) SetSubscriptionResolver(resolve func(*ai.Model) bool)
- func (s *StatusLine) SetSuppressedByExtFooter(v bool)
- func (s *StatusLine) SetThinkingLevel(level string)
- func (s *StatusLine) SetTurnContextUsage(u *ai.Usage)
- func (s *StatusLine) SetUsageTotalsSource(source func() footerUsageTotals)
- func (s *StatusLine) SetUsingSubscription(v bool)
- func (s *StatusLine) SetWorking(b bool)
- func (s *StatusLine) SetWorkingMessage(message string)
- type StdinBuffer
- func (b *StdinBuffer) Clear()
- func (b *StdinBuffer) Flush() []string
- func (b *StdinBuffer) FlushTimeout() time.Duration
- func (b *StdinBuffer) HasPendingFlush() bool
- func (b *StdinBuffer) ProcessBytes(data []byte) []string
- func (b *StdinBuffer) ProcessString(s string) []string
- func (b *StdinBuffer) ProcessTerminalBytes(data []byte) []string
- type StdinBufferOptions
- type SteppedSubmenu
- type SteppedSubmenuOptions
- type SteppedSubmenuStep
- type SubprocessHost
- type SubprocessUIBridge
- type TUIUIContext
- func (u *TUIUIContext) Confirm(title, message string) bool
- func (u *TUIUIContext) Input(title, placeholder string) (string, bool)
- func (u *TUIUIContext) Notify(message, level string)
- func (u *TUIUIContext) Select(title string, options []string) (string, bool)
- func (u *TUIUIContext) SetStatus(key, text string)
- func (u *TUIUIContext) SetWidget(key string, lines []string)
- type ThinkingBudgetsSettings
- type ThinkingLevelEntry
- type ThinkingSelectorComponent
- type TierError
- type ToolCallEventResult
- type TrailingEntries
- type UpdateBinary
- type UpdateManifest
- type UsageEntry
- type WarningSettings
Constants ¶
const ( // Session lifecycle EventSessionStart = "session_start" EventSessionInfoChanged = "session_info_changed" EventSessionShutdown = "session_shutdown" EventSessionBeforeSwitch = "session_before_switch" EventSessionBeforeFork = "session_before_fork" EventSessionBeforeCompact = "session_before_compact" EventSessionCompact = "session_compact" EventSessionCompactFailed = "session_compact_failed" EventSessionBeforeTree = "session_before_tree" EventSessionTree = "session_tree" // Agent loop EventAgentStart = "agent_start" EventAgentEnd = "agent_end" EventAgentBeforeSettle = "agent_before_settle" EventAgentSettled = "agent_settled" EventTurnStart = "turn_start" EventTurnEnd = "turn_end" EventBeforeAgentStart = "before_agent_start" EventMessageStart = "message_start" EventMessageUpdate = "message_update" EventMessageEnd = "message_end" // Tools EventToolCall = "tool_call" EventToolResult = "tool_result" EventToolExecutionStart = "tool_execution_start" EventToolExecutionUpdate = "tool_execution_update" EventToolExecutionEnd = "tool_execution_end" // Context / provider EventContext = "context" EventContextWithSystem = "context_with_system" EventBeforeProviderRequest = "before_provider_request" EventAfterProviderResponse = "after_provider_response" EventBeforeProviderHeaders = "before_provider_headers" // Models / input EventModelSelect = "model_select" EventThinkingLevelSelect = "thinking_level_select" EventInput = "input" // User-initiated bash command (`!cmd` / `!!cmd`). // Mirrors upstream `user_bash` event emitted by // `interactive-mode.ts:5040-5045::extensionRunner.emitUserBash`. // Payload: {type, command, excludeFromContext, cwd}. EventUserBash = "user_bash" // Resources EventResourcesDiscover = "resources_discover" )
Extension event name constants: mirror upstream event type strings.
const APP_TITLE = "PiG"
pig divergence (D2): title says "PiG", not "pi": separate binary and config root.
const AppName = "pig"
AppName is the binary/CLI name. Distinct from upstream pi to avoid PATH collisions and shared-config corruption.
const BugReportCustomEntryType = "pi.bug-report"
BugReportCustomEntryType is the session custom-entry type recorded after a report is written. It matches upstream so Pi and PiG read the same history.
const ( // BugReportIssueURL is the PiG issue form that /bug links to. PiG // reports go to the PiG repository, never to Pi's report gateway (D62). BugReportIssueURL = "https://github.com/MichaelKinsy/PiG/issues/new" )
const CONFIG_DIR_NAME = "." + AppName
CONFIG_DIR_NAME is the per-project config directory name. Mirrors upstream's CONFIG_DIR_NAME export.
const CurrentSessionVersion = 3
CurrentSessionVersion mirrors upstream `CURRENT_SESSION_VERSION = 3`. Bumping this requires a migration step in session_resume.go.
const DefaultThinkingLevel = "medium"
DefaultThinkingLevel mirrors upstream's defaults.ts:
export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
Used as the fallback when settings.json does not define defaultThinkingLevel. Thinking-level initialization consumes it.
If upstream ever changes the default, the tripwire test in defaults_test.go fails, surfacing the drift on the next sync.
const ENV_AGENT_DIR = "PIG_CODING_AGENT_DIR"
ENV_AGENT_DIR overrides the config directory. Mirrors upstream ENV_AGENT_DIR export.
const ENV_SESSION_DIR = "PIG_CODING_AGENT_SESSION_DIR"
ENV_SESSION_DIR overrides the session storage directory. Mirrors upstream ENV_SESSION_DIR export.
const EnvRadiusGateway = "PI_RADIUS_GATEWAY"
EnvRadiusGateway overrides the Radius gateway origin for GetRadiusGatewayURL. In Pi 0.87.1 only the experimental server and relay read it; the built-in provider always uses ai.DefaultRadiusGateway.
const PackageName = "pig"
PackageName identifies the installed package/binary for self-update messaging. Mirrors upstream PACKAGE_NAME export.
const RadiusProviderID = ai.RadiusProviderID
RadiusProviderID is the built-in Radius provider ID.
const UpdateSignatureHeader = "X-Pig-Release-Signature"
UpdateSignatureHeader carries the base64 Ed25519 signature over the exact update manifest response bytes.
Variables ¶
var CacheWarmingModes = []CacheWarmingMode{"off", "streaming", "idle"}
CacheWarmingModes lists the modes in Pi's order (CACHE_WARMING_MODES).
var DefaultUpdateTrustRoot string
DefaultUpdateTrustRoot is an optional build-time Ed25519 public key in PEM form. Distributor installers normally seed the same public key through the update-trust.pem sidecar beside update-url.
var DefaultUpdateURL string
DefaultUpdateURL is the built-in update-manifest URL. It is empty in stock pig and is set at build time for a product binary via:
-ldflags "-X github.com/MichaelKinsy/PiG/internal/codingagent.DefaultUpdateURL=<url>"
so a product release can configure its update source. Stock Pig and Piglet builds never set it: update transport is product/environment policy.
var ErrInteractiveCrashed = errors.New("interactive mode crashed")
ErrInteractiveCrashed reports that Run recovered a crash it already printed and recorded; the caller exits 1 without printing it again.
var ErrUnknownSlashCommand = errors.New("unknown slash command")
ErrUnknownSlashCommand signals that a slash command was not found in the registry. The caller should pass the original text to the LLM as a regular message (matches upstream behavior where unknown slashes are sent as-is).
var InstalledPigVersion string
InstalledPigVersion is the running Pig distribution version. cmd/pig sets it before dispatch so receipt validation can bind the executable to its release.
var PigletBinaryRelease string
PigletBinaryRelease is the baked Piglet/Piglet Binary release version. It is empty for stock Pig and set via ldflags for a Piglet Binary. When set it marks the running binary as an immutable baked release whose composition cannot be drifted in place (see ResolveSelfUpdateTier). It is the single source of truth for the baked release identity; cmd/pig copies its ldflags value here at startup.
var SupportedImageMIMEs = []string{
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
}
SupportedImageMIMEs lists the formats we accept from the clipboard. Order = preference (matches upstream SUPPORTED_IMAGE_MIME_TYPES).
Functions ¶
func AgentActivityOutcome ¶
func AgentActivityOutcome(messages []agent.AgentMessage, runErr error) extension.AgentActivityOutcome
AgentActivityOutcome reports the terminal state of the most recent low-level run to an agent_before_settle boundary.
func AgentDir ¶
func AgentDir() string
AgentDir returns the configured writable agent directory. The environment override matches the directory selected by the main CLI and RPC mode.
func AgentLoopEventType ¶
func AgentLoopEventType(ev agent.AgentEvent) string
AgentLoopEventType returns the extension event type DispatchAgentLoopEvent dispatches for ev, or "" for an event it does not dispatch.
func AuthenticatedProviders ¶
AuthenticatedProviders returns the subset of ReachableProviders for which credentials are detectable in the environment / auth.json / model registry, without probing the network.
- github-copilot: OAuth credential present and not expired
- openai/openrouter/groq: <ID_UPPER>_API_KEY env var set OR registry has any non-empty APIKey entry for the provider
- ollama: OLLAMA_HOST env set (cheap heuristic; we do NOT probe localhost:11434: picking ollama with no daemon running is a user error caught at switch time)
agentDir is the pig config dir (typically ~/.pig/agent). auth.json and models.json are read from there.
func BugReportArchiveFileName ¶
BugReportArchiveFileName names a report archive. Mirrors upstream bugReportArchiveFileName with PiG's command name (D2).
func BugReportIssueLink ¶
func BugReportIssueLink(metadata BugReportMetadata, archiveName, upstreamVersion string) string
BugReportIssueLink returns a prefilled PiG bug-form URL. It carries only the form's own fields: a title from the first line of the description (bounded), the PiG and Pi versions, the platform, and the archive name to attach. It never carries session content, settings, or paths.
func CanonicalizePath ¶
CanonicalizePath resolves a path to its canonical filesystem form, following symlinks. If resolution fails (for example because the path does not exist yet), it falls back to the raw path. Mirrors upstream canonicalizePath.
func CatalogRoot ¶
CatalogRoot returns the managed catalog materialization root.
func CleanupWindowsSelfUpdateQuarantine ¶
func CleanupWindowsSelfUpdateQuarantine(packageDir string)
CleanupWindowsSelfUpdateQuarantine removes the images an earlier npm self-update quarantined beside packageDir. A previous pig process may still be exiting and holding one, so a failure leaves the quarantine for the next start.
func ClearCrashLog ¶
func ClearCrashLog(path string)
ClearCrashLog removes the crash log; a failure leaves the records for the next report. Mirrors upstream clearCrashLog.
func CompareChangelogEntries ¶
func CompareChangelogEntries(a, b ChangelogEntry) int
CompareChangelogEntries returns -1, 0, or 1 mirroring upstream `compareVersions`. Callers use it to filter entries newer than a version.
func CompareVersions ¶
CompareVersions compares strict semantic versions. Returns -1 if a<b, 1 if a>b, and 0 when equal or when either side is malformed. Callers parsing release metadata must reject malformed remote versions before comparison; the zero fallback here keeps development/CI local versions non-disruptive.
func ConfigRoot ¶
func ConfigRoot() string
ConfigRoot returns the pig configuration root directory.
Resolution order:
- $PIG_HOME if set and non-empty
- $XDG_CONFIG_HOME/pig if XDG_CONFIG_HOME is set
- ~/.pig (default)
All pig state: agent dir, auth.json, sessions, agents, subagent output - lives under this root. Never touches ~/.pi/.
func ContainerRemediation ¶
ContainerRemediation is the exact authenticated pull/redeploy instruction for an OCI image or Piglet Image deployment. Raw Pig performs no transport and knows no product topology, so a deployment that owns a specific redeploy operation supplies it verbatim through PIG_REDEPLOY_INSTRUCTION. Pig still owns the surrounding facts (artifact identity, executable, and the guarantee that the running image is never rewritten); only the operation comes from the product. Without that metadata Pig falls back to the generic image pull, which is correct for a plain OCI/container install but not for an orchestrator-managed deployment.
func ConvertImageBytesToPng ¶
ConvertImageBytesToPng mirrors upstream convertImageBytesToPng: it decodes the image, applies its EXIF orientation, and re-encodes it as PNG. It returns nil when the bytes cannot be decoded or encoded, where upstream returns null (conversion failed or Photon unavailable).
func ConvertToPng ¶
func ConvertToPng(base64Data, mimeType string) *tui.ConvertedImage
ConvertToPng mirrors upstream convertToPng: the Kitty graphics protocol requires PNG (f=100), so a non-PNG base64 image is converted. PNG input is returned unchanged; nil is upstream's null for a failed conversion.
func CrashLogPath ¶
CrashLogPath returns the crash log location for an agent directory.
func CreateShareTrailingEntries ¶
func CreateShareTrailingEntries(state ShareState, parentID *string, timestamp string) []any
CreateShareTrailingEntries returns the trailing pi.share entry carrying the system prompt and tool schemas for the session viewer. Mirrors upstream createShareTrailingEntries.
func CurrentSystemMessage ¶
func CurrentSystemMessage(messages []agent.AgentMessage) *ai.SystemMessage
CurrentSystemMessage replays every projected system message into the current prompt and tool state (pi-ai getCurrentSystemMessage).
func DefaultAgentDir ¶
func DefaultAgentDir() string
DefaultAgentDir returns the default <ConfigRoot>/agent directory.
func DefaultSkillsDir ¶
func DefaultSkillsDir() string
DefaultSkillsDir returns the user agent's skills directory.
func DispatchAgentLoopEvent ¶
func DispatchAgentLoopEvent(runner *inproc.Runner, ev agent.AgentEvent, currentMessage *extension.AgentMessage)
DispatchAgentLoopEvent maps one agent-loop event to the extension runner, mirroring upstream agent-session.ts::_emitExtensionEvent (lines 640-711). It is called from coding.Session.forwardAgentEvents so that every driver - interactive, rpc, and print: dispatches agent-loop events from one place (the session), matching upstream where _handleAgentEvent awaits _emitExtensionEvent before notifying listeners. currentMessage carries the in-flight message across message_start → message_update, as upstream passes event.message on message_update; the caller owns the storage (the session funnel is single-goroutine, so no lock is needed).
func ExpandPromptTemplate ¶
func ExpandPromptTemplate(line string, templates []PromptTemplate) (string, bool)
ExpandPromptTemplate consumes a `/name [args]` line. If `name` matches a loaded template, returns the expanded body with arg substitution applied and ok=true. Otherwise returns ("", false). Lines without a leading `/` always return ("", false). Mirrors upstream `expandPromptTemplate` (v0.69.0:293-308).
func ExpandSkillCommand ¶
ExpandSkillCommand expands a "/skill:name [args]" string to the skill XML block. Returns (expanded, true) on success, ("", false) if the text doesn't start with "/skill:" or the named skill isn't in skills.
Mirrors upstream _expandSkillCommand (agent-session.ts:1124-1151). The XML block format matches upstream:
<skill name="..." location="..."> References are relative to <dir>. <body> </skill>
Args (if any) are appended after the block separated by two newlines.
func ExpandTildePath ¶
ExpandTildePath expands a leading ~ in a filesystem path. Mirrors upstream expandTildePath.
func ExportSessionForShare ¶
func ExportSessionForShare(filePath string, session *Session, state ShareState) (string, error)
ExportSessionForShare writes the current branch with the export-only pi.share presentation entry. Mirrors upstream exportSessionForShare.
func ExportSessionToJsonl ¶
func ExportSessionToJsonl(session *Session, outputPath string, createTrailingEntries TrailingEntries) (string, error)
ExportSessionToJsonl writes the session's current branch (and optional trailing entries) to outputPath, resolved against the process working directory, or to session-<ISO timestamp>.jsonl there when outputPath is empty. It returns the resolved path. Mirrors upstream exportSessionToJsonl.
func ExtensionForImageMIME ¶
ExtensionForImageMIME returns the canonical file extension for a supported image MIME, or "" if unknown. Matches upstream's extensionForImageMimeType.
func ExtensionsInLoadOrder ¶
ExtensionsInLoadOrder appends in-process builtins after configured extensions. Upstream resource-loader.ts loads path extensions first, then inline factories, and the runner preserves that order for dispatch and conflict ownership.
func FindExtensionStackMatches ¶
func FindExtensionStackMatches(stack string, extensions []ExtensionStackMetadata) []string
FindExtensionStackMatches returns loaded extensions whose source files occur in stack frames.
func FormatCacheWarmingStatus ¶
func FormatCacheWarmingStatus(status CacheWarmingStatus, now int64) string
FormatCacheWarmingStatus is the one-line status /session shows. now is a Unix millisecond time.
func FormatCacheWarmingUsage ¶
func FormatCacheWarmingUsage(entry UsageEntry) string
FormatCacheWarmingUsage is the one-line transcript text for persisted cache-warming usage.
func FormatChangelogForChat ¶
func FormatChangelogForChat(entries []ChangelogEntry) string
FormatChangelogForChat takes parsed entries and produces the markdown block /changelog appends to the chat. Mirrors upstream `handleChangelogCommand` (interactive-mode.ts:4795-4814) shape:
- reverse the entries (so they read oldest-at-top, newest-at-bottom within the inline block: matches upstream's `.reverse().map(...)`),
- join their content with two newlines,
- wrap in a bold "What's New" header and horizontal-rule "borders" (pig's markdown renderer paints `---` as a separator line; this is the parity-correct equivalent of upstream's DynamicBorder).
Empty input returns the upstream-verbatim "No changelog entries found." fallback so a user with a missing/empty CHANGELOG sees a sensible message instead of an empty bordered block.
func FormatCrashExtensionHint ¶
FormatCrashExtensionHint formats the warning shown for matching extensions.
func FormatNoModelSelectedMessage ¶
func FormatNoModelSelectedMessage() string
func FormatNoModelsAvailableMessage ¶
func FormatNoModelsAvailableMessage() string
func FormatPathRelativeToCwdOrAbsolute ¶
FormatPathRelativeToCwdOrAbsolute returns a slash-normalized path relative to cwd when possible, otherwise the cleaned absolute path.
func GenerateEntryID ¶
GenerateEntryID returns a random hexadecimal entry ID.
func GenerateSessionID ¶
GenerateSessionID returns a time-ordered UUIDv7 for a new session.
func GetCacheWarmingDelayMs ¶
GetCacheWarmingDelayMs refreshes at 90% of the TTL while preserving at least ten seconds of margin. The bool is false when the TTL is too short.
func GetCwdRelativePath ¶
GetCwdRelativePath returns the slash-normalized path relative to cwd when filePath resolves inside cwd, or "" when it is outside cwd.
func GetPackageDir ¶
func GetPackageDir() string
GetPackageDir is the installation directory of a compiled pig: the directory holding the running executable, as upstream getPackageDir returns for a compiled binary. It returns "" when the executable cannot be located.
func GetProjectTrustParentPath ¶
GetProjectTrustParentPath returns the parent trust key, or "" at the root.
func GetProjectTrustPath ¶
GetProjectTrustPath returns the canonical trust key for a cwd.
func GetPromptCacheTtlMs ¶
GetPromptCacheTtlMs is the lifetime of the prompt cache entry a request writes, from the model's promptCache tier for the retention the request used. The bool is false when the model has no lifetime for that tier.
PiG's StreamOptions has no per-request cacheRetention (providers read only PI_CACHE_RETENTION), so the retention comes from the environment, as it does for every upstream session request.
func GetRadiusGatewayURL ¶
func GetRadiusGatewayURL() string
GetRadiusGatewayURL returns the Radius gateway origin, honoring PI_RADIUS_GATEWAY. Like upstream's `??`, a set but empty value is used.
func GetSelfUpdateUnavailableInstruction ¶
GetSelfUpdateUnavailableInstruction returns the fallback self-update hint. pig divergence (D39): pig is a standalone binary, so the instruction points at `pig update self` (configured update source) or the download/container ladder, not an npm package-manager command.
func GetUpdateInstruction ¶
GetUpdateInstruction returns the user-facing self-update instruction.
func GitInstallRoot ¶
GitInstallRoot returns the managed Git checkout root for one settings scope.
func HasTrustRequiringProjectResources ¶
HasTrustRequiringProjectResources reports whether cwd has project-local inputs governed by project trust. Project config entries are checked only in cwd; .agents/skills is checked from cwd through every ancestor. The user's ~/.agents/skills is global input and never requires project trust.
func ImmutableBinaryRemediation ¶
ImmutableBinaryRemediation is the exact, non-looping instruction for a baked Piglet/Piglet Binary release. Pig does not drift the baked composition in place; the owning release is rebuilt and re-pulled.
func IsContextOverflow ¶
func IsContextOverflow(msg *agent.AssistantMessage, contextWindow int) bool
IsContextOverflow reports whether an assistant message represents a context overflow. It is pi-ai's isContextOverflow (ai.IsContextOverflow).
func IsRecoverableLength ¶
func IsRecoverableLength(msg *agent.AssistantMessage, desiredMaxOutput int) bool
IsRecoverableLength reports whether a provider stopped for length before reaching the model's original output limit. The limit must be the model value before request-time context clamping. It is pi-ai's isRecoverableLength (ai.IsRecoverableLength).
func IsReplayable ¶
func IsReplayable(model *ai.Model, options ai.StreamOptions) bool
IsReplayable reports whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based thinking derives budget_tokens from max_tokens, and Anthropic keys the message cache on that budget, so only adaptive thinking replays safely.
func IsRetryableError ¶
func IsRetryableError(msg *agent.AssistantMessage, contextWindow int) bool
IsRetryableError reports whether an assistant message is a transient provider or transport error worth retrying. A context overflow is not retryable: compaction handles it. Mirrors upstream AgentSession._isRetryableError, which applies pi-ai's isContextOverflow and isRetryableAssistantError.
func IsStdoutTakenOver ¶
func IsStdoutTakenOver() bool
IsStdoutTakenOver reports whether a takeover is currently active.
func IsWSL ¶
IsWSL reports whether the process runs under Windows Subsystem for Linux, where Windows executables are reachable through interop. Ports utils/wsl.ts isWSL: WSL_DISTRO_NAME or WSLENV, else a /proc/version that names Microsoft or WSL. getenv and readFile are injected so tests never read the host.
func KeybindingsFile ¶
func ListSkills ¶
ListSkills enumerates skill directories under skillsDir, applying symlink dedup. Returns skill names (the directory basenames) sorted alphabetically. A skill directory is anything containing a `SKILL.md` file.
A skill can be linked from multiple configured roots. Resolve symlinks so the user sees one entry in the /skills selector.
func MarkPathIgnoredByCloudSync ¶
func MarkPathIgnoredByCloudSync(path string)
MarkPathIgnoredByCloudSync best-effort marks a directory as ignored by cloud sync providers. Mirrors upstream markPathIgnoredByCloudSync.
func ModelNetworkEnabled ¶
func ModelNetworkEnabled() bool
ModelNetworkEnabled mirrors ModelRuntime.modelNetworkEnabled (PI_OFFLINE === undefined). PIG_OFFLINE is Pig's product-neutral alias.
func NPMInstallRoot ¶
NPMInstallRoot returns the managed npm project for one settings scope.
func NormalizePromptContent ¶
func NormalizePromptContent(content []ai.UserContentBlock, autoResize bool, model *ai.Model) []ai.UserContentBlock
NormalizePromptContent applies the selected model's profile once, before new images enter history. Prompt failures become text hints, unlike tool results.
func NormalizeToolResultImages ¶
func NormalizeToolResultImages(result agent.AgentToolResult, autoResize bool) agent.AgentToolResult
func OpenExternalEditor ¶
func OpenExternalEditor(ctx context.Context, initial string, configuredEditor string) (string, error)
OpenExternalEditor writes initial into a tempfile, runs the user's editor on it (stdio inherited), and returns the file contents on success. On editor non-zero exit OR read error, returns initial unchanged plus a non-nil error.
The tempfile is always removed before this function returns.
Caller is responsible for:
- restoring cooked-mode terminal before calling (so the editor's stdin/stdout/stderr inherit a usable TTY);
- re-entering raw mode and triggering a full re-render after.
Reference: upstream openExternalEditor() in modes/interactive/interactive-mode.ts.
func ParsePromptArgs ¶
ParsePromptArgs splits an argument string into tokens, respecting single- and double-quoted runs. Whitespace outside quotes is the separator. Mirrors upstream `parseCommandArgs` (core/prompt-templates.ts v0.69.0:24-52).
func PigletArtifactsDir ¶
func PigletArtifactsDir() string
PigletArtifactsDir returns the managed Piglet artifact store.
func PigletRecordsDir ¶
func PigletRecordsDir() string
PigletRecordsDir returns the managed Piglet record store. Records live outside Piglet discovery so they never masquerade as editable source.
func PigletsDir ¶
func PigletsDir() string
PigletsDir returns the user-owned Piglet source directory.
func PlatformKey ¶
func PlatformKey() string
PlatformKey returns the "<goos>/<goarch>" manifest key for the current platform.
func PrepareWindowsNpmSelfUpdate ¶
PrepareWindowsNpmSelfUpdate readies the npm installation holding exePath for npm to replace: it clears an earlier quarantine and quarantines the images this process loaded from it, which for pig is the running executable. It does nothing outside Windows.
func ProjectConfigDir ¶
ProjectConfigDir returns the workspace-local Pig configuration root.
func ProjectStateDir ¶
ProjectStateDir returns one additive capability's workspace-scoped state directory.
func ProviderLoginHelp ¶
func ProviderLoginHelp() string
ProviderLoginHelp mirrors upstream auth-guidance.ts.
func QuarantineWindowsNativeDependencies ¶
QuarantineWindowsNativeDependencies moves each image this process loaded from packageDir into the quarantine and copies it back. Windows lets a loaded image be renamed but not overwritten or deleted, so the copy leaves npm free to replace packageDir while this process runs.
func RFC3339NowNano ¶
func RFC3339NowNano() string
RFC3339NowNano returns the current UTC time as a nanosecond-precision RFC3339 string: the timestamp format used in every session entry's header. Centralised here so coding/ doesn't have to duplicate the formatting choice.
func RawStdoutWriter ¶
RawStdoutWriter returns an `io.Writer` that writes to the pre-takeover stdout. Convenient for passing into helpers like `printToolsForMessages` that expect a Writer interface.
func ReachableProviders ¶
ReachableProviders returns the set of provider IDs that coding.BuildModel has an explicit `case` for. Anything else falls through BuildModel's default branch which constructs an OpenAI-compatible client: fine for OpenAI-shaped APIs but a silent mis-route for Anthropic/Bedrock/Vertex/etc. that would error at first request.
SINGLE SOURCE OF TRUTH. Keep this set aligned with coding/model.go::BuildModel so provider additions touch one map entry here.
func ReadClipboardImage ¶
ReadClipboardImage reads a PNG/JPEG/WebP/GIF from the system clipboard. Returns (nil, "", nil) when the clipboard holds no image : this is not an error case, just "nothing to paste".
func ReadClipboardImageContext ¶
ReadClipboardImageContext reads a clipboard image while parent remains active. Ctrl+V passes its renderer lifetime so teardown cancels command probes and joins the operation instead of leaving terminal I/O behind.
func RedactBugReportJSON ¶
RedactBugReportJSON copies a JSON-encodable value, replacing the value of every sensitive key with "<redacted>" and redacting URLs in strings. Mirrors upstream redactJsonValue.
func RedactBugReportURL ¶
RedactBugReportURL strips credentials and secret-looking query parameters from an absolute URL, including a URL nested after a scheme prefix such as "git:https://...". Other strings are returned unchanged. Mirrors upstream redactUrl.
func RenderLoginHeader ¶
func RenderLoginHeader(definition extension.ValidatedLoginDefinition, width int, options LoginHeaderOptions) []string
RenderLoginHeader renders a validated definition with Pig's fixed native login template. It is local and deterministic; callers choose terminal color and glyph capabilities before rendering.
func RenderTreeASCII ¶
func RenderTreeASCII(root *SessionTreeNode) string
RenderTreeASCII renders a SessionTreeNode as an ASCII tree. Exported wrapper so the coding package can produce /tree output without duplicating the renderer.
func ReportDiagnostics ¶
func ReportDiagnostics(diagnostics []AgentSessionRuntimeDiagnostic)
ReportDiagnostics writes diagnostics to stderr for non-interactive modes: "Error: " in red, "Warning: " in yellow, and info dimmed, colored only when stderr is a terminal. Mirrors upstream main.ts reportDiagnostics.
func RestoreStdout ¶
func RestoreStdout()
RestoreStdout undoes a `TakeOverStdout`. Closes the pipe writer (signalling the copy goroutine to drain + exit), waits for the goroutine, then restores `os.Stdout`. Safe to call without a matching takeover (no-op).
func RunAgentBeforeSettle ¶
func RunAgentBeforeSettle( ctx context.Context, session *Session, a *agent.Agent, runner *inproc.Runner, outcome extension.AgentActivityOutcome, ) (bool, error)
RunAgentBeforeSettle emits the final settlement boundary, commits its durable drafts, refreshes the agent transcript, and reports whether one more provider run can start.
func RunInputHandlers ¶
func RunInputHandlers(ctx context.Context, runner *inproc.Runner, text string, images []ai.ImageContent, source extension.InputSource, streamingBehavior string) (string, []ai.ImageContent, bool, error)
RunInputHandlers runs the extension input handlers for user input and returns the text and images to use, or handled when an extension consumed it. A transform without images keeps the original images, and a handler failure is returned for the caller to report. Mirrors upstream agent-session.ts _runInputHandlers; coding.Session.RunInputHandlers is the Session entry point every mode uses.
func RunMigrations ¶
func RunMigrations(cwd, agentDir string) (migratedAuthProviders []string, deprecationWarnings []string, err error)
RunMigrations runs all one-time startup migrations. A failed auth.json write is an error, as upstream's uncaught write throws. Mirrors upstream runMigrations (migrations.ts:259-268).
func RunPackageManagerUpdate ¶
func RunPackageManagerUpdate(cmd *SelfUpdateCommand) error
RunPackageManagerUpdate executes the owning manager's update command. It is the only mutation path for the package-manager tier; once it starts, a failure surfaces from this tier and never falls through to another.
func SaveClipboardImageToTempFile ¶
SaveClipboardImageToTempFile writes the bytes to $TMPDIR/pig-clipboard-<nanos>.<ext> and returns the absolute path. The caller is responsible for cleanup; for a paste-into-editor flow we leave the file around so the model can read it back.
func SelectStartupSession ¶
func SelectStartupSession( currentLoader func() ([]SessionInfo, error), allLoader func() ([]SessionInfo, error), opts StartupUIOptions, ) (path string, selected bool, err error)
SelectStartupSession runs the same session selector used by /resume before cwd-bound runtime services exist. It returns selected=false on cancellation.
func SelfReplace ¶
SelfReplace downloads bin, verifies its SHA256, and atomically replaces the running executable. Unix-only: replacing a running .exe in place needs the Windows quarantine dance pig does not implement, so on Windows it returns an error directing the user to reinstall.
func SelfReplaceAt ¶
func SelfReplaceAt(ctx context.Context, client *http.Client, bin UpdateBinary, exePath string) error
SelfReplaceAt downloads bin, verifies its SHA256, and atomically replaces the executable at exePath. It is the standalone-tier replacement entry point used after tier resolution has proven exePath. Unix-only: on Windows it returns an error directing the user to reinstall.
func SelfReplaceAtWithCommit ¶
func SelfReplaceAtWithCommit( ctx context.Context, client *http.Client, bin UpdateBinary, exePath string, commit func() error, ) error
SelfReplaceAtWithCommit replaces exePath and then commits its ownership metadata. If commit fails, the previous executable is restored before the error returns, so a failed receipt update cannot strand a new binary with stale provenance.
func SelfUpdateFallback ¶
func SelfUpdateFallback() string
SelfUpdateFallback is the actionable instruction shown when self-update cannot run automatically (no source, unreachable, unsupported platform, or a read-only install). It degrades gracefully: point at the working command when a source is configured, otherwise the ladder of set-a-URL / download / pull the container image.
func SerializeSessionBranch ¶
func SerializeSessionBranch(header SessionHeader, branch []SessionEntry, now time.Time, createTrailingEntries TrailingEntries) (string, error)
SerializeSessionBranch writes a fresh session header, the current branch with each entry's parentId chained to the previous entry, and any trailing entries, one JSON object per line. Mirrors upstream serializeSessionBranch.
func SessionEntryToContextMessages ¶
func SessionEntryToContextMessages(entry SessionEntry) []agent.AgentMessage
SessionEntryToContextMessages projects one entry into context messages before context edits (session-manager.ts sessionEntryToContextMessages). State-only entries project to nothing.
func ShowStartupInput ¶
func ShowStartupInput(title, placeholder string, opts StartupUIOptions) (value string, selected bool, err error)
ShowStartupInput displays the extension text-input surface before runtime services exist. It returns selected=false when the user cancels.
func ShowStartupSelector ¶
func ShowStartupSelector(title string, options []string, opts StartupUIOptions) (index int, selected bool, err error)
ShowStartupSelector displays a small pre-runtime choice list. It returns selected=false when the user cancels.
func SkillDiagnostics ¶
SkillDiagnostics validates a skill against the Agent Skills metadata rules. A missing description prevents model discovery; other findings are warnings.
func StartupKeybindHints ¶
func StartupKeybindHints(km *KeybindingsManager) string
StartupKeybindHints renders the compact keybinding hint line shown under the startup banner, mirroring upstream interactive-mode's compact startup instructions (interrupt · clear/exit · / commands · ! bash · <expand> more). Keys resolve through the supplied manager so user remaps are reflected; a nil manager falls back to the built-in defaults.
func StateDir ¶
StateDir returns one additive capability's user-scoped state directory. Namespaces are code-owned identifiers, not user-provided paths.
func SubstitutePromptArgs ¶
SubstitutePromptArgs returns content with `$1`, `${1:-default}`, `${@:N:L}`, `${@:-default}`, `$ARGUMENTS`, `$@` expanded against args. Mirrors upstream `substituteArgs` (core/prompt-templates.ts). A `:-default` value is used when the target arg is missing or empty. Substitution runs in a single pass, so argument values are NOT re-scanned for `$N`/`$@`/`$ARGUMENTS` patterns.
func SystemMessageFromAgentMessage ¶
func SystemMessageFromAgentMessage(message agent.AgentMessage) (ai.SystemMessage, bool)
SystemMessageFromAgentMessage reads a projected system-role message.
func TakeOverStdout ¶
func TakeOverStdout() error
TakeOverStdout redirects subsequent `os.Stdout` writes to `os.Stderr`. Idempotent: a second call before `RestoreStdout` is a no-op. The saved original stdout is reachable via `WriteRawStdout` for explicit framed-output callers.
func ToolResultEventContent ¶
func ToolResultEventContent(result agent.AgentToolResult) []any
ToolResultEventContent preserves text and images at the extension boundary.
func ToolResultEventOverride ¶
func ToolResultEventOverride(result *extension.ToolResultEventResult) agent.AfterToolCallResult
ToolResultEventOverride decodes the runner's complete, chained content. An empty image list intentionally clears images replaced by a text-only result.
func UnsupportedRemediation ¶
UnsupportedRemediation is the concrete reinstall/download instruction for a read-only, Windows, or unknown-provenance installation. It never repeats the failed self-update command.
func UpdateSourceURL ¶
func UpdateSourceURL() string
UpdateSourceURL resolves the update-manifest URL. Resolution order:
- PIG_UPDATE_URL env (explicit per-invocation override);
- a sidecar file at <config-root>/update-url, written by an installer that knows its origin at install time (a generic, transport-neutral seam: any distributor may write it; pig reads only the URL, never product data);
- the build-time embedded DefaultUpdateURL, set by a product release build;
- empty (no update source configured).
The sidecar lets an installer seed the update source for a downloaded binary without a Go toolchain (the binary is not rebuilt) and without modifying the user's shell rc. It carries one URL line; pig never writes it.
func WireModelOperations ¶
func WireModelOperations(bridge ModelOperationBridge, bindings ModelOperationBindings) func()
WireModelOperations installs one Session-owned extension model surface and returns its catalog-listener detach function.
func WriteBugReportArchive ¶
func WriteBugReportArchive(bundle BugReportBundle, path string) (err error)
WriteBugReportArchive writes the bundle as a deflated zip at path. The file is created exclusively so an existing file is never overwritten.
func WriteRawStdout ¶
WriteRawStdout writes `text` to the original (pre-takeover) stdout, bypassing the redirect. Use for explicit framed output: print-mode final text, RPC JSON-RPC frames. When no takeover is active, this is equivalent to writing directly to `os.Stdout`.
func WriteStandaloneReceipt ¶
WriteStandaloneReceipt atomically records a verified standalone install. Installers create the initial receipt; a successful standalone update replaces it with the newly installed release and digest.
Types ¶
type AgentSessionRuntimeDiagnostic ¶
AgentSessionRuntimeDiagnostic is one startup diagnostic. Type is "info", "warning", or "error". Mirrors upstream AgentSessionRuntimeDiagnostic.
func CollectSettingsDiagnostics ¶
func CollectSettingsDiagnostics(settingsManager *SettingsManager) []AgentSessionRuntimeDiagnostic
CollectSettingsDiagnostics drains the manager's settings errors as warnings naming the settings file, or the scope when no file backs the error. Mirrors upstream collectSettingsDiagnostics.
func DeduplicateDiagnostics ¶
func DeduplicateDiagnostics(diagnostics []AgentSessionRuntimeDiagnostic) []AgentSessionRuntimeDiagnostic
DeduplicateDiagnostics removes duplicate type/message diagnostics while preserving their first occurrence. Startup and runtime settings managers can report the same file error. Mirrors upstream deduplicateDiagnostics.
type BashExecOptions ¶
type BashExecOptions = tools.BashExecOptions
BashExecOptions is a type alias for tools.BashExecOptions.
type BashExecutionEntry ¶
type BashExecutionEntry struct {
SessionEntryBase
Role string `json:"-"` // always "bashExecution"; set on read
Command string `json:"-"`
Output string `json:"-"`
ExitCode *int `json:"-"`
Cancelled bool `json:"-"`
Truncated bool `json:"-"`
FullOutputPath string `json:"-"`
ExcludeFromContext bool `json:"-"`
}
BashExecutionEntry persists a `!cmd` invocation. Mirrors upstream `BashExecutionMessage` (.upstream/v0.69.0/.../core/messages.ts:29-43 + agent-session.ts:2585-2614).
Wire shape, matching upstream session-manager.ts:834:
{
"type": "message", // outer SessionMessageEntry discriminator
"id": "...",
"parentId": "...",
"timestamp": "...",
"message": {
"role": "bashExecution", // inner discriminator
"command": "ls",
"output": "...",
"exitCode": 0,
"cancelled": false,
"truncated": false,
"fullOutputPath": "...",
"timestamp": 1234567890,
"excludeFromContext": false
}
}
In-memory we synthesize `Base.Type = "bash_execution"` after parsing so all existing exhaustive switches continue to work; this is a pure internal label, not on the wire. Older PiG sessions with top-level `type: "bash_execution"` still load through the legacy branch in UnmarshalJSON.
`ExcludeFromContext` is set when the user invoked `!!cmd`: the entry persists for transcript purposes but is filtered out of agent hand-off so the LLM doesn't see it.
func (BashExecutionEntry) MarshalJSON ¶
func (b BashExecutionEntry) MarshalJSON() ([]byte, error)
MarshalJSON serializes to upstream's wire shape (type:"message" + nested).
func (*BashExecutionEntry) UnmarshalJSON ¶
func (b *BashExecutionEntry) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts BOTH the new wire shape (type:"message" with inner role:"bashExecution") AND the legacy pig shape (type:"bash_execution" with flat top-level fields), so older session files still load.
type BashExecutionMessage ¶
type BashExecutionMessage struct {
Role string `json:"role"` // "bashExecution"
Command string `json:"command"`
Output string `json:"output"`
ExitCode *int `json:"exitCode"`
Cancelled bool `json:"cancelled"`
Truncated bool `json:"truncated"`
FullOutputPath string `json:"fullOutputPath,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
ExcludeFromContext bool `json:"excludeFromContext,omitempty"`
}
BashExecutionMessage is the inner `message` payload upstream uses for bash entries. Mirrors messages.ts:29-43 byte-for-byte.
type BashResult ¶
type BashResult = tools.BashResult
BashResult is a type alias for tools.BashResult. All fields are identical; existing callers compile without changes.
func ExecuteBash ¶
func ExecuteBash(ctx context.Context, command, cwd string, shell tools.ShellConfig, opts BashExecOptions) (BashResult, error)
ExecuteBash runs command under shell in cwd. Delegates to tools.ExecuteBash. See tools/bash_executor.go for the canonical implementation.
type BinaryUpdate ¶
type BinaryUpdate struct {
CurrentVersion string
LatestVersion string
Notes string
Binary UpdateBinary
Command string // the command that applies it, e.g. "pig update self"
}
BinaryUpdate describes an available newer release for the current platform.
func CheckForBinaryUpdate ¶
func CheckForBinaryUpdate(ctx context.Context, client *http.Client, currentVersion string) *BinaryUpdate
CheckForBinaryUpdate fetches the update manifest and reports a newer release for the current platform, or nil when up to date, no source is configured, or the source is unreachable. It never surfaces an error: a startup update check is best-effort and must not disrupt the session.
type BranchSummaryConfig ¶
type BranchSummaryConfig struct {
ReserveTokens int `json:"reserveTokens,omitempty"`
SkipPrompt bool `json:"skipPrompt,omitempty"`
// contains filtered or unexported fields
}
BranchSummaryConfig mirrors compaction.BranchSummarySettings but lives here to avoid an import cycle.
type BranchSummaryEntry ¶
type BugReportAssistantDiagnostic ¶
type BugReportAssistantDiagnostic struct {
EntryID string `json:"entryId"`
Timestamp string `json:"timestamp"`
Provider string `json:"provider"`
Model string `json:"model"`
API string `json:"api"`
StopReason string `json:"stopReason"`
RawStopReason string `json:"rawStopReason,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
Diagnostics []ai.AssistantMessageDiagnostic `json:"diagnostics"`
}
BugReportAssistantDiagnostic is one failed or diagnosed assistant turn.
type BugReportAuthStatus ¶
type BugReportAuthStatus struct {
Configured bool `json:"configured"`
Source string `json:"source,omitempty"`
Label string `json:"label,omitempty"`
}
BugReportAuthStatus mirrors upstream's provider auth status record.
type BugReportBundle ¶
type BugReportBundle struct {
Metadata BugReportMetadata
Diagnostics BugReportDiagnostics
SessionJSONL *string
Summary *string
}
BugReportBundle is everything one report archive contains.
type BugReportDiagnostics ¶
type BugReportDiagnostics struct {
SchemaVersion int `json:"schemaVersion"`
SessionID string `json:"sessionId"`
EntryCount int `json:"entryCount"`
AssistantMessageCount int `json:"assistantMessageCount"`
Assistant []BugReportAssistantDiagnostic `json:"assistant"`
Crashes []CrashRecord `json:"crashes"`
}
BugReportDiagnostics is diagnostics.json.
func CollectBugReportDiagnostics ¶
func CollectBugReportDiagnostics(sessionID string, entries []SessionEntry, crashes []CrashRecord) BugReportDiagnostics
CollectBugReportDiagnostics collects failed assistant turns without conversation content, plus the crash log records without their notified flag. Mirrors upstream collectBugReportDiagnostics.
type BugReportEnvironment ¶
type BugReportEnvironment struct {
Version string `json:"version"`
UserAgent string `json:"userAgent"`
Runtime string `json:"runtime"`
Platform string `json:"platform"`
Arch string `json:"arch"`
OSRelease string `json:"osRelease"`
OSVersion string `json:"osVersion"`
Shell *string `json:"shell"`
Terminal BugReportTerminalEnv `json:"terminal"`
// PiEnvironmentVariables lists PI_* names only; values never leave the
// machine. PigEnvironmentVariables lists PiG's own PIG_* names.
PiEnvironmentVariables []string `json:"piEnvironmentVariables"`
PigEnvironmentVariables []string `json:"pigEnvironmentVariables"`
}
BugReportEnvironment describes the running PiG process without secrets.
type BugReportExtension ¶
type BugReportExtension struct {
Path string `json:"path"`
}
BugReportExtension describes one loaded extension by its resolved path.
type BugReportExtensionError ¶
type BugReportExtensionError struct {
Error string `json:"error"`
}
BugReportExtensionError is one extension load failure. PiG's subprocess host reports failures as messages without a separate path.
type BugReportFile ¶
BugReportFile is one archive member.
func BugReportFiles ¶
func BugReportFiles(bundle BugReportBundle) ([]BugReportFile, error)
BugReportFiles lists the archive members in upstream order.
type BugReportInputs ¶
type BugReportInputs struct {
Version string
SessionID string
CWD string
MessageCount int
Model *ai.Model
Provider *BugReportProvider
ThinkingLevel string
ExtensionPaths []string
ExtensionErrors []string
GlobalSettings Settings
ProjectSettings Settings
Entries []SessionEntry
Branch []SessionEntry
Header SessionHeader
}
BugReportInputs is the process state a report describes. The interactive host fills it; tests construct it directly.
type BugReportMetadata ¶
type BugReportMetadata struct {
SchemaVersion int `json:"schemaVersion"`
ID string `json:"id"`
CreatedAt string `json:"createdAt"`
Hint *string `json:"hint"`
Environment BugReportEnvironment `json:"environment"`
Session BugReportSessionInfo `json:"session"`
Model *BugReportModel `json:"model"`
Provider *BugReportProvider `json:"provider"`
ThinkingLevel string `json:"thinkingLevel"`
Extensions []BugReportExtension `json:"extensions"`
ExtensionErrors []BugReportExtensionError `json:"extensionErrors"`
Settings BugReportSettings `json:"settings"`
}
BugReportMetadata is report.json. Field order follows upstream.
func CollectBugReportMetadata ¶
func CollectBugReportMetadata(inputs BugReportInputs, options BugReportOptions, summaryIncluded bool, now time.Time) (BugReportMetadata, error)
CollectBugReportMetadata builds report.json. Mirrors upstream collectBugReportMetadata.
type BugReportModel ¶
type BugReportModel struct {
Provider string `json:"provider"`
ID string `json:"id"`
Name string `json:"name"`
API string `json:"api"`
BaseURL string `json:"baseUrl"`
Reasoning bool `json:"reasoning"`
Input []string `json:"input"`
ContextWindow int `json:"contextWindow"`
MaxTokens int `json:"maxTokens"`
SamplingParams any `json:"samplingParams"`
Compat any `json:"compat"`
ThinkingLevelMap ai.ThinkingLevelMap `json:"thinkingLevelMap"`
HeaderNames []string `json:"headerNames"`
}
BugReportModel describes the current model without credentials.
type BugReportOptions ¶
BugReportOptions are the user's consent choices.
type BugReportProvider ¶
type BugReportProvider struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL *string `json:"baseUrl"`
HeaderNames []string `json:"headerNames"`
AuthStatus BugReportAuthStatus `json:"authStatus"`
UsingOAuth bool `json:"usingOAuth"`
RegisteredByExtension bool `json:"registeredByExtension"`
}
BugReportProvider describes the current model's provider without credentials.
type BugReportSessionEntryData ¶
type BugReportSessionEntryData struct {
ID string `json:"id"`
CreatedAt string `json:"createdAt"`
Hint *string `json:"hint"`
SessionIncluded bool `json:"sessionIncluded"`
SummaryIncluded bool `json:"summaryIncluded"`
Delivery string `json:"delivery"`
Path string `json:"path,omitempty"`
}
BugReportSessionEntryData is the custom entry /bug records in the session. Mirrors upstream BugReportSessionEntryData; delivery is always "zip".
type BugReportSessionInfo ¶
type BugReportSessionInfo struct {
ID string `json:"id"`
Included bool `json:"included"`
SummaryIncluded bool `json:"summaryIncluded"`
MessageCount int `json:"messageCount"`
CWD string `json:"cwd,omitempty"`
}
BugReportSessionInfo records what the report shares about the session.
type BugReportSettings ¶
BugReportSettings holds the redacted global and project settings.
type BugReportTerminalEnv ¶
type BugReportTerminalEnv struct {
Term *string `json:"term"`
Program *string `json:"program"`
ProgramVersion *string `json:"programVersion"`
Colorterm *string `json:"colorterm"`
Tmux bool `json:"tmux"`
SSH bool `json:"ssh"`
CI bool `json:"ci"`
}
BugReportTerminalEnv records terminal identification variables.
type BuiltinSlashCommand ¶
type BuiltinSlashCommand struct {
Name string
Aliases []string
Description string
// ArgumentHint is shown after the command in autocomplete (e.g.
// "<provider/model>"). Optional. Mirrors upstream argumentHint.
ArgumentHint string
Handler SlashHandler
// Hidden commands dispatch normally but are omitted from /help and
// autocomplete. Mirrors upstream commands handled inline in the submit
// handler that are absent from the canonical slash-commands.js list
// (e.g. /debug).
Hidden bool
}
BuiltinSlashCommand is the canonical shape for every command exposed to users. Aliases are first-class. (Note: upstream pi does NOT alias /exit → /quit; only /quit exists. We match that behavior: no alias.)
func BuiltinSlashCommands ¶
func BuiltinSlashCommands() []BuiltinSlashCommand
BuiltinSlashCommands returns the canonical builtin slash command list (name + description + aliases). Single source of truth for `/help`, the dispatcher, and the autocomplete popup - mirrors upstream's `BUILTIN_SLASH_COMMANDS` re-export from `core/slash-commands.ts`.
type CacheWarmRequest ¶
type CacheWarmRequest struct {
Model *ai.Model
Context ai.TranscriptContext
Options ai.StreamOptions
}
CacheWarmRequest is the request whose prompt cache entry should be kept warm, exactly as it was sent.
type CacheWarmer ¶
type CacheWarmer struct {
// contains filtered or unexported fields
}
CacheWarmer keeps one prompt cache entry alive by re-sending its request with a one-token output cap before the entry expires. Start replaces any previous run; warm requests never extend the fixed safety windows.
Upstream's unawaited setTimeout refresh maps to an owned task: a timer whose callback the warmer tracks, cancelled through the run's context and drained by Wait.
func NewCacheWarmer ¶
func NewCacheWarmer(stream agent.StreamFn, sessionManager CacheWarmerSessionManager, getMode func() CacheWarmingMode, decide CacheWarmingDecide) *CacheWarmer
NewCacheWarmer creates a warmer. A nil decide keeps Pi's own decision.
func (*CacheWarmer) Cancel ¶
func (w *CacheWarmer) Cancel()
Cancel stops warming. Mirrors upstream cancel().
func (*CacheWarmer) Close ¶
func (w *CacheWarmer) Close()
Close cancels warming for good, as upstream dispose does: later Start calls are ignored and, once Close returns, no refresh reports to OnWarmed, even one still persisting its usage entry. Close waits for a report already in progress, after cancelling that report's context.
func (*CacheWarmer) OnAgentSettled ¶
func (w *CacheWarmer) OnAgentSettled()
OnAgentSettled moves the run to its idle phase, or stops it in streaming mode.
func (*CacheWarmer) OnModeChanged ¶
func (w *CacheWarmer) OnModeChanged()
OnModeChanged reconciles an active run after the persisted mode changes.
func (*CacheWarmer) SetOnWarmed ¶
func (w *CacheWarmer) SetOnWarmed(onWarmed func(context.Context, UsageEntry))
SetOnWarmed sets the callback that receives the persisted usage entry after each successful refresh. Its context is cancelled when Close starts; a callback blocked on delivery must return once it is, because Close waits for it. The callback must not call Close.
func (*CacheWarmer) Start ¶
func (w *CacheWarmer) Start(request CacheWarmRequest, isCurrent func() bool)
Start keeps the prompt cache entry written by request warm while isCurrent holds.
func (*CacheWarmer) Status ¶
func (w *CacheWarmer) Status() CacheWarmingStatus
Status reports the current warming state and the policy inputs that produced it.
func (*CacheWarmer) Wait ¶
func (w *CacheWarmer) Wait()
Wait blocks until every scheduled or in-flight refresh has finished, then releases the closed warmer's provider and Session references. Call it after Close.
type CacheWarmerSessionManager ¶
type CacheWarmerSessionManager interface {
AppendUsage(kind, provider, model string, usage ai.Usage, note string) (UsageEntry, error)
GetBranch() []SessionEntry
}
CacheWarmerSessionManager is the Session surface the warmer uses. Mirrors Pick<SessionManager, "appendUsage" | "getBranch">.
type CacheWarmingAction ¶
type CacheWarmingAction string
CacheWarmingAction is Pi's warm-or-stop decision.
const ( CacheWarmingActionWarm CacheWarmingAction = "warm" CacheWarmingActionStop CacheWarmingAction = "stop" )
type CacheWarmingDecide ¶
type CacheWarmingDecide func(context.Context, CacheWarmingDecisionEvent) (CacheWarmingAction, error)
CacheWarmingDecide lets an extension override a decision. An error falls back to Pi's decision.
type CacheWarmingDecision ¶
type CacheWarmingDecision struct {
// Phase is "streaming" while the agent run that sent the request is still
// active, then "idle".
Phase string `json:"phase"`
// WarmCost is the price of this refresh: a cache read of the prompt plus
// one output token.
WarmCost float64 `json:"warmCost"`
// MissCost is the extra price of the next real request if the entry is lost.
MissCost float64 `json:"missCost"`
// ContinuationProbability estimates the chance that a real request
// arrives before the entry expires.
ContinuationProbability float64 `json:"continuationProbability"`
// ExpectedSavings is ContinuationProbability*MissCost - WarmCost.
ExpectedSavings float64 `json:"expectedSavings"`
// EconomicsAvailable is false when the prompt size or prices are unknown.
EconomicsAvailable bool `json:"economicsAvailable"`
// Action is "warm" when ExpectedSavings is at least $0.05.
Action CacheWarmingAction `json:"action"`
}
CacheWarmingDecision holds the inputs and outcome of one warm-or-stop decision, as shown by /session.
type CacheWarmingDecisionEvent ¶
type CacheWarmingDecisionEvent struct {
Type string `json:"type"`
WarmCost float64 `json:"warmCost"`
MissCost float64 `json:"missCost"`
ContinuationProbability float64 `json:"continuationProbability"`
Action CacheWarmingAction `json:"action"`
}
CacheWarmingDecisionEvent is fired before each refresh with Pi's decision filled in; an extension may override Action. Field order matches the payload upstream emits.
type CacheWarmingMode ¶
type CacheWarmingMode string
CacheWarmingMode selects when prompt caches are kept warm. Mirrors upstream settings-manager.ts CacheWarmingMode.
type CacheWarmingStatus ¶
type CacheWarmingStatus struct {
// State is "inactive", "scheduled" (a refresh timer is armed), or
// "refreshing" (a warm request is in flight).
State string `json:"state"`
// Reason says why nothing is scheduled.
Reason string `json:"reason,omitempty"`
// NextWarmAt is the Unix millisecond time of the next decision, or 0.
NextWarmAt int64 `json:"nextWarmAt,omitempty"`
// Decision is the pending decision, or the decision that stopped warming.
Decision *CacheWarmingDecision `json:"decision,omitempty"`
// ExtensionOverride is true when an extension changed Decision.Action.
ExtensionOverride bool `json:"extensionOverride,omitempty"`
}
CacheWarmingStatus is the warmer state /session reports.
type CatalogRefreshOptions ¶
CatalogRefreshOptions selects providers and whether network access is allowed. An empty Providers list refreshes every dynamic provider.
type CatalogRefreshResult ¶
CatalogRefreshResult mirrors upstream ModelsRefreshResult.
func RefreshModelCatalogs ¶
func RefreshModelCatalogs(ctx context.Context, registry *ModelRegistry) (CatalogRefreshResult, error)
RefreshModelCatalogs shares concurrent interactive all-catalog refreshes for a registry while keeping each caller's cancellation independent. The last departing caller cancels the operation; a later caller can start a new refresh without waiting for abandoned work to settle.
type ChangelogEntry ¶
type ChangelogEntry struct {
Major int
Minor int
Patch int
Content string // includes the `## [x.y.z]` header line itself, trimmed
}
ChangelogEntry is one parsed `## [x.y.z]` block.
func GetNewEntries ¶
func GetNewEntries(entries []ChangelogEntry, sinceVersion string) []ChangelogEntry
GetNewEntries returns the subset of entries whose version is strictly newer than sinceVersion (a "x.y.z" string). Mirrors upstream getNewEntries (utils/changelog.ts:84-96).
func ParseChangelog ¶
func ParseChangelog(content string) []ChangelogEntry
ParseChangelog walks the markdown content of a CHANGELOG.md and returns one ChangelogEntry per `## [x.y.z]`-style header. Order is the order found in the file (typical convention: newest first). Malformed entries are silently skipped: matches upstream behavior (errors only logged via console.error).
type ChatViewport ¶
type ChatViewport struct {
Root tui.Component
Transcript *tui.ScrollView
}
ChatViewport is the fullscreen layout root and its transcript scroll view. Mirrors upstream ChatViewport.
func CreateChatViewport ¶
func CreateChatViewport(options ChatViewportOptions) ChatViewport
CreateChatViewport builds the shared fullscreen transcript and fixed input-dock layout. Mirrors upstream createChatViewport.
type ChatViewportOptions ¶
type ChatViewportOptions struct {
Document tui.Component
PendingMessages tui.Component
Status tui.Component
Editor tui.Component
WidgetsAbove tui.Component
WidgetsBelow tui.Component
Scrollbar string
ScrollbarTrackStyle func(text string) string
ScrollbarThumbStyle func(text string) string
}
ChatViewportOptions mirrors upstream ChatViewportOptions (chat-viewport.ts). WidgetsAbove and WidgetsBelow are optional (nil omits the dock slot); Scrollbar "" takes upstream's "auto" default; nil styles take the ScrollView defaults.
type CompactionConfig ¶
CompactionConfig mirrors compaction.CompactionSettings but lives here to avoid an import cycle (compaction imports codingagent for SessionEntry).
type CompactionEntry ¶
type CompactionEntry struct {
SessionEntryBase
Summary string `json:"summary"`
FirstKeptEntryID string `json:"firstKeptEntryId"`
TokensBefore int `json:"tokensBefore"`
Details any `json:"details,omitempty"`
Usage *ai.Usage `json:"usage,omitempty"`
FromHook bool `json:"fromHook"`
// SystemMessage is the complete prompt and tool state at this compaction
// boundary. It is absent when the projected context has no system state.
SystemMessage json.RawMessage `json:"systemMessage,omitempty"`
}
CompactionEntry field order matches Pi's appendCompaction object literal so Pig-written entries serialize with the same key order.
type CompactionModelOverride ¶
type CompactionModelOverride struct {
ReserveTokens *int `json:"reserveTokens,omitempty"`
KeepRecentTokens *int `json:"keepRecentTokens,omitempty"`
}
CompactionModelOverride mirrors upstream CompactionModelOverride. Pointers keep an explicit zero, as upstream's `override ?? ordinary` does.
type CompactionSettingsJSON ¶
type CompactionSettingsJSON struct {
Enabled *bool `json:"enabled,omitempty"`
// ReserveTokens and KeepRecentTokens are pointers so an explicit 0 is
// kept, as upstream's `?? default` does.
ReserveTokens *int `json:"reserveTokens,omitempty"`
KeepRecentTokens *int `json:"keepRecentTokens,omitempty"`
// ModelOverrides maps exact "provider/modelId" keys to token settings
// that take precedence for that model.
ModelOverrides map[string]CompactionModelOverride `json:"modelOverrides,omitempty"`
}
CompactionSettingsJSON mirrors upstream Settings.compaction JSON shape (settings-manager.ts:74). Pointer to *bool for enabled to distinguish absent vs. explicitly-false.
type ContextEditEntry ¶
type ContextEditEntry struct {
SessionEntryBase
TargetID string `json:"targetId"`
Replacement *ContextEditReplacement `json:"replacement"`
}
ContextEditEntry is an append-only change to one earlier entry's contribution to model context (session-manager.ts ContextEditEntry). A nil Replacement serializes as null and omits the target from model context; a replacement changes only the target's content. The target entry itself is never rewritten.
type ContextEditReplacement ¶
type ContextEditReplacement struct {
Content json.RawMessage `json:"content"`
}
ContextEditReplacement is the non-null replacement of a context_edit entry (session-manager.ts ContextEditEntry.replacement). Content is the JSON string or content-block array that replaces the target's content (ContextEditableContent).
type ContextFile ¶
ContextFile holds a loaded project context file (AGENTS.override.md, AGENTS.md, or CLAUDE.md). Mirrors upstream resource-loader.ts::loadProjectContextFiles return shape.
func LoadProjectContextFiles ¶
func LoadProjectContextFiles(cwd, agentDir string) []ContextFile
LoadProjectContextFiles discovers and loads project context files from the agent config directory and every ancestor directory from cwd up to the filesystem root.
Load order (matches upstream resource-loader.ts:76-115):
- Agent config dir (e.g. ~/.pig/): global context
- Ancestor directories from root down to cwd: project context
Within each directory, AGENTS.override.md replaces that directory's regular AGENTS/CLAUDE candidate while ancestor layering remains intact. Duplicate paths are skipped by their loaded path. In a nested linked worktree, the main checkout's same-named context file is skipped when the worktree root supplies its own copy.
type CrashInput ¶
type CrashInput struct {
Kind string
Message string
Stack string
SessionFile string
CWD string
Version string
}
CrashInput describes a crash to record.
type CrashRecord ¶
type CrashRecord struct {
Timestamp string `json:"timestamp"`
Version string `json:"version"`
Kind string `json:"kind"`
Message string `json:"message"`
Stack *string `json:"stack"`
SessionFile *string `json:"sessionFile"`
CWD string `json:"cwd"`
Notified bool `json:"notified,omitempty"`
}
CrashRecord is one crashes.json entry. Mirrors upstream CrashRecord; Kind is "uncaught_exception" or "fatal_error".
func ReadCrashLog ¶
func ReadCrashLog(path string) []CrashRecord
ReadCrashLog returns the valid records, or none when the file is missing or unreadable. A record needs a string timestamp and message. Mirrors upstream readCrashLog.
func RecordCrash ¶
func RecordCrash(crash CrashInput, path string, now time.Time) (CrashRecord, bool)
RecordCrash appends a crash, keeping the newest five. It is best effort for callers that are already crashing: it reports ok=false when nothing was written. Mirrors upstream recordCrash.
func TakeUnnotifiedCrash ¶
func TakeUnnotifiedCrash(path string, now time.Time) (CrashRecord, bool)
TakeUnnotifiedCrash returns the newest crash from the last seven days that has not been announced, and marks every record announced. Mirrors upstream takeUnnotifiedCrash.
type CustomEntry ¶
type CustomEntry struct {
SessionEntryBase
CustomType string `json:"customType"`
Data any `json:"data,omitempty"`
}
type CustomMessageEntry ¶
type CustomMessageEntry struct {
SessionEntryBase
CustomType string `json:"customType"`
Content any `json:"content"` // string | []ContentBlock
Display bool `json:"display"`
Details any `json:"details,omitempty"`
}
type ExtUIContext ¶
type ExtUIContext struct {
// contains filtered or unexported fields
}
ExtUIContext implements extension.UIContext for interactive mode. Subprocess extensions' Select/Confirm/Input/Editor calls are dispatched here via the UIBridge.
func (*ExtUIContext) AddAutocompleteProvider ¶
func (u *ExtUIContext) AddAutocompleteProvider(factory extension.AutocompleteProviderFactory)
AddAutocompleteProvider accepts subprocess async suggestion sources. It does not instantiate an in-process provider factory.
func (*ExtUIContext) Confirm ¶
func (u *ExtUIContext) Confirm(ctx context.Context, title, message string, opts extension.ExtensionUIDialogOptions) (bool, error)
Confirm shows a Yes/No selector. Mirrors upstream's showExtensionConfirm (interactive-mode.ts:1996-2003).
func (*ExtUIContext) Editor ¶
Editor shows a multi-line editor in the editor slot. Mirrors upstream's showExtensionEditor in interactive-mode.ts, which creates an ExtensionEditorComponent and swaps it into the editorContainer.
func (*ExtUIContext) GetAllThemes ¶
func (u *ExtUIContext) GetAllThemes() []extension.ThemeMeta
GetAllThemes lists the themes the user can switch to, mirroring upstream's getAllThemes (getAvailableThemesWithPaths). Path is empty for built-in themes, matching upstream's `path: string | undefined`.
func (*ExtUIContext) GetEditorComponent ¶
func (u *ExtUIContext) GetEditorComponent() any
func (*ExtUIContext) GetEditorText ¶
func (u *ExtUIContext) GetEditorText() string
func (*ExtUIContext) GetTheme ¶
func (u *ExtUIContext) GetTheme(name string) (extension.Theme, error)
GetTheme loads a theme by name without switching to it, mirroring upstream's getTheme (getThemeByName).
func (*ExtUIContext) GetToolsExpanded ¶
func (u *ExtUIContext) GetToolsExpanded() bool
func (*ExtUIContext) Input ¶
func (u *ExtUIContext) Input(ctx context.Context, title, placeholder string, _ extension.ExtensionUIDialogOptions) (string, error)
Input shows a text input in the editor slot. Blocks until the user submits (Enter) or cancels (Esc). Mirrors upstream's showExtensionInput in interactive-mode.ts.
func (*ExtUIContext) Notify ¶
func (u *ExtUIContext) Notify(message, kind string)
func (*ExtUIContext) OnRemoteTerminalInput ¶
func (u *ExtUIContext) OnRemoteTerminalInput(extensionName string, handler extension.RemoteTerminalInputHandler) func()
OnRemoteTerminalInput registers a subprocess extension's listener. The input loop asks it off the loop and applies its verdict in input order.
func (*ExtUIContext) OnTerminalInput ¶
func (u *ExtUIContext) OnTerminalInput(handler extension.TerminalInputHandler) func()
func (*ExtUIContext) PasteToEditor ¶
func (u *ExtUIContext) PasteToEditor(text string)
func (*ExtUIContext) ReportsDialogInitiation ¶
func (u *ExtUIContext) ReportsDialogInitiation() bool
ReportsDialogInitiation reports that Select, Confirm, Input, and Editor mark their call initiated once the dialog is queued for installation.
func (*ExtUIContext) RunRemoteOverlay ¶
func (u *ExtUIContext) RunRemoteOverlay(opts extension.RemoteOverlayOptions, host extension.RemoteOverlayHost, onHandle func(extension.RemoteOverlayHandle)) (any, bool)
RunRemoteOverlay opens a remote-backed overlay (used by the subprocess bridge to implement ctx.ui.custom from TypeScript extensions). Blocks until the remote producer signals close.
The input loop runs in this goroutine: safe because subprocess extension calls are dispatched from the host read loop, which is distinct from the interactive Run() loop. While this overlay is open, the originating /command or event handler is awaiting its response on Node, so the interactive editor is idle and the goroutine that opens this overlay has exclusive read access to os.Stdin (same invariant as Select/Input/Editor above).
func (*ExtUIContext) Select ¶
func (u *ExtUIContext) Select(ctx context.Context, title string, options []string, _ extension.ExtensionUIDialogOptions) (string, error)
Select shows a generic option list in the editor slot. Blocks until the user picks an option or cancels (Esc). Mirrors upstream's showExtensionSelector in interactive-mode.ts using the standalone ExtensionSelectorComponent (NO filter input, fixed title row, fixed hint row).
func (*ExtUIContext) SetEditorComponent ¶
func (u *ExtUIContext) SetEditorComponent(factory any)
func (*ExtUIContext) SetEditorText ¶
func (u *ExtUIContext) SetEditorText(text string)
func (*ExtUIContext) SetFooter ¶
func (u *ExtUIContext) SetFooter(factory any)
func (*ExtUIContext) SetHeader ¶
func (u *ExtUIContext) SetHeader(factory any)
func (*ExtUIContext) SetHiddenThinkingLabel ¶
func (u *ExtUIContext) SetHiddenThinkingLabel(label string)
func (*ExtUIContext) SetLogin ¶
func (u *ExtUIContext) SetLogin(definition extension.LoginDefinition) error
func (*ExtUIContext) SetStatus ¶
func (u *ExtUIContext) SetStatus(key, text string)
SetStatus forwards a keyed status to the footer and requests a render, like upstream setExtensionStatus. Extensions call it from their own timers, so the render request is what paints it while the session is idle.
func (*ExtUIContext) SetTheme ¶
func (u *ExtUIContext) SetTheme(theme any) extension.SetThemeResult
SetTheme switches the active theme and persists the choice, mirroring upstream's setTheme: apply, then record it in settings when it differs.
Upstream also accepts a Theme instance. A subprocess extension cannot send one, and no in-process caller does, so only the name form is accepted.
func (*ExtUIContext) SetTitle ¶
func (u *ExtUIContext) SetTitle(title string)
func (*ExtUIContext) SetToolsExpanded ¶
func (u *ExtUIContext) SetToolsExpanded(expanded bool)
func (*ExtUIContext) SetWidget ¶
func (u *ExtUIContext) SetWidget(key string, content any, opts extension.ExtensionWidgetOptions)
func (*ExtUIContext) SetWorkingIndicator ¶
func (u *ExtUIContext) SetWorkingIndicator(options extension.WorkingIndicatorOptions)
func (*ExtUIContext) SetWorkingMessage ¶
func (u *ExtUIContext) SetWorkingMessage(message string)
func (*ExtUIContext) SetWorkingVisible ¶
func (u *ExtUIContext) SetWorkingVisible(visible bool)
func (*ExtUIContext) Theme ¶
func (u *ExtUIContext) Theme() extension.Theme
type ExtensionConflict ¶
ExtensionConflict is a tool or flag that an extension registers after another extension, at a different path, already registered it.
func DetectExtensionConflicts ¶
func DetectExtensionConflicts(exts []extension.Extension) []ExtensionConflict
DetectExtensionConflicts mirrors upstream resource-loader.ts detectExtensionConflicts. It walks extensions in load order, keeps the first owner of each tool and flag name, and reports every later registration by another extension. All extensions stay loaded; upstream adds the conflicts to the extension load errors.
type ExtensionContext ¶
type ExtensionContext struct {
UI ExtensionUIContext
HasUI bool
CWD string
Session *Session
Model *ai.Model
IsIdle func() bool
// IsProjectTrusted mirrors upstream ExtensionContext.isProjectTrusted
// (types.ts:332). Trust can be granted mid-session, so it is a function
// rather than a snapshot.
IsProjectTrusted func() bool
AbortSignal context.Context
AbortFunc context.CancelFunc
}
ExtensionContext is shared mutable state for the agent loop. Passed to slash command handlers and event bridges.
type ExtensionStackMetadata ¶
type ExtensionStackMetadata struct {
Path string
ResolvedPath string
SourceInfo ResourceSourceInfo
}
ExtensionStackMetadata is the loaded extension provenance used to attribute stack frames after a crash.
type ExtensionUIContext ¶
type ExtensionUIContext interface {
Select(title string, options []string) (string, bool)
Confirm(title, message string) bool
Input(title, placeholder string) (string, bool)
Notify(message, level string)
SetStatus(key, text string)
SetWidget(key string, lines []string)
}
ExtensionUIContext mirrors the upstream ExtensionUIContext interface. In interactive mode this is backed by the TUI; in headless/print mode it falls back to no-op implementations.
type InteractiveMode ¶
type InteractiveMode struct {
// contains filtered or unexported fields
}
InteractiveMode runs the full interactive TUI session.
func NewInteractiveMode ¶
func NewInteractiveMode(opts InteractiveOptions) *InteractiveMode
NewInteractiveMode creates an interactive session.
func (*InteractiveMode) Run ¶
func (m *InteractiveMode) Run(ctx context.Context) (err error)
Run renders the initial editor and footer even with quiet startup, then blocks in the interactive loop until the user exits.
func (*InteractiveMode) ShutdownFromSignal ¶
func (m *InteractiveMode) ShutdownFromSignal()
ShutdownFromSignal emits session_shutdown so extensions can run cleanup before the process tears down, and is safe to call more than once.
Upstream's signal-triggered shutdown emits extension cleanup BEFORE touching the terminal, because teardown such as removing sockets does not write to the tty and must not be skipped if a later terminal-restore write fails (interactive-mode.ts shutdown({fromSignal: true})).
Ordering matters in pig for a second reason: extension subprocesses are spawned with the root context, so cancelling it kills them. If SIGTERM cancelled the context first, the shutdown event would be delivered to processes that no longer exist and extensions would silently never clean up. The caller therefore invokes this before cancelling.
type InteractiveOptions ¶
type InteractiveOptions struct {
CWD string
AgentDir string
Model *ai.Model
Settings Settings
// SettingsManager provides read/write access to global settings.
// Wired by main.go via coding.Services.
SettingsManager *SettingsManager
// SystemPrompt overrides the assembled system prompt. If empty,
// callers should build one via prompts.BuildDefaultPrompt and pass
// it in.
SystemPrompt string
// SystemPromptOptions mirrors upstream
// `BuildSystemPromptOptions` (system-prompt.ts:8-25). It carries
// the structured inputs that produced SystemPrompt (custom prompt,
// tools, append text, context files, skills) and is passed verbatim
// to extensions on every before_agent_start event so they can
// inspect what pi has loaded without re-discovering resources.
//
// upstream: agent-session.ts:_rebuildSystemPrompt
SystemPromptOptions extension.BuildSystemPromptOptions
// AllowedTools restricts which tool names may execute. nil means no
// restriction; a non-nil empty map blocks every tool. Mirrors the
// `tools:` allowlist on agent .md frontmatter.
AllowedTools map[string]struct{}
// ActiveBuiltinTools, when non-nil, restricts which built-in coding
// tools are active (caller/extension tools unaffected). nil = all
// built-in tools. Mirrors upstream defaultActiveToolNames (sdk.ts:244):
// CLI default [read, bash, edit, write]; grep/find/ls inactive unless
// requested via --tools.
ActiveBuiltinTools map[string]struct{}
// ExcludedTools is a denylist of tool names made non-callable, gating
// built-in and extension tools alike. Mirrors upstream excludedToolNames
// (sdk.ts:246) + isAllowedTool (agent-session.ts:2288).
ExcludedTools map[string]struct{}
// NoBuiltinTools hides built-in tools while leaving extension/custom tools.
NoBuiltinTools bool
// PromptPaths lists additional prompt-template directories.
// Mirrors upstream `additionalPromptTemplatePaths`.
// Directories are searched after the default <agentDir>/prompts/ and
// <cwd>/.pig/prompts/ (last-wins by name, same as project scope).
PromptPaths []string
// SessionDir overrides the on-disk session directory used by /new,
// /resume, and other interactive session-management flows.
SessionDir string
// SessionID specifies an exact session ID for new sessions.
// Mirrors upstream --session-id (v0.76.0). When non-empty and no
// existing session matches, Create uses this ID instead of
// generating a random one.
SessionID string
// ThemePaths lists additional theme files/directories to load.
ThemePaths []string
// NoPromptTemplates disables prompt template discovery.
NoPromptTemplates bool
// NoThemes disables custom theme discovery from disk.
NoThemes bool
// UnknownFlags carries CLI flags not claimed by the core parser so
// extensions can resolve their registered values at runtime.
UnknownFlags map[string]any
// BeforeToolCall hooks run at agent-loop time and can block tool
// execution. The allowlist hook provides defense in depth alongside
// the registration-time filter.
BeforeToolCall []agent.BeforeToolCallHook
// SessionHandle, when non-nil, is the pre-constructed agent +
// on-disk session that InteractiveMode wraps for the TUI.
// Constructed by the caller via coding.NewSession from the public
// SDK package; main.go does the bridging between coding.* and
// internal/codingagent.*. When nil, Run() returns an error: the
// SDK is the only supported construction path post-Chunk F.
//
// Mutually exclusive with ResumePath: if SessionHandle is set,
// the caller is responsible for having loaded the session via
// coding.NewSession's ResumePath field.
SessionHandle InteractiveSessionHandle
// ContextUsage returns the live Session projection estimate for footer updates.
ContextUsage func() (tokens *int, contextWindow int)
// ModelBuilder constructs an *ai.Model from a "<provider>/<id>"
// spec. Wired by main.go to coding.BuildModel: the public SDK
// can't be imported from internal/codingagent (cycle), so the
// caller injects the constructor. nil disables /model switching
// (handler falls back to print-only).
ModelBuilder func(spec string) (*ai.Model, error)
// ModelLookup resolves a provider/model identity through the Session-owned runtime.
ModelLookup func(providerID, modelID string) *ai.Model
ModelCatalog func() []*ai.Model
// RequestAuthRuntime is the composed checkAuth/getAuth surface used by
// warning-only auth checks. Wired by main.go from the same credential and
// provider configuration used for model requests.
RequestAuthRuntime *RequestAuthRuntime
// ModelRegistry is the model registry for auth-aware operations
// (Refresh, GetAvailable, HasConfiguredAuth). Wired by main.go.
// nil is safe; post-login refresh is skipped.
// Mirrors upstream session.modelRegistry (interactive-mode.ts:4394).
ModelRegistry *ModelRegistry
// ExtensionRunner is the new-style (`coding/extension`) runner.
// May be nil during tests or when no extensions are loaded.
// Events are dispatched through this runner via event_bridge.go.
ExtensionRunner *inproc.Runner
// ExtensionContext is the live extension context shared with the
// runner. Caller-supplied to ensure extCtx.Session points at the
// SAME on-disk session SessionHandle wraps.
ExtensionContext *ExtensionContext
// ResumePath, when non-empty, is loaded as the active session at
// startup. The agent's message history is rebuilt from
// session.BuildContext() and the transcript is replayed inline so
// the user sees prior conversation.
ResumePath string
// InitialMessage, when non-empty, is auto-submitted to the agent
// immediately after the TUI initialises. Mirrors upstream's
// `initialMessage` plumbing at
// `.upstream/current/packages/coding-agent/src/cli/initial-message.ts`.
// Sourced by main.go from positional args + piped stdin so users
// can `pig "hello"`, `pig < file.txt`, or pipe + run.
InitialMessage string
InitialImages []ai.ImageContent
// InitialMessages are the positional messages after the first. Each is
// sent as its own prompt once the previous one settles (upstream
// initialMessages).
InitialMessages []string
// AppVersion is the binary version string used to detect
// changelog-seen state. Set to UpstreamVersion (the port target).
// gate the startup "what's new" changelog notification.
// Mirrors upstream this.version in InteractiveMode constructor.
AppVersion string
// PackageUpdateChecker, if set, is invoked asynchronously at startup
// to check for available package updates. The returned strings are
// the display names of packages with available updates. When the
// returned slice is non-empty, an "X package updates available"
// banner is shown. Mirrors upstream checkForPackageUpdates +
// showPackageUpdateNotification (interactive-mode.ts:660-665, 3449).
PackageUpdateChecker func() []string
// BinaryUpdateChecker, if set, is invoked asynchronously at startup and
// returns a newer-release notice for the pig binary itself, or nil. pig
// divergence (D39): standalone-binary self-update. The notice names the
// command that applies it (e.g. `pig update self`).
BinaryUpdateChecker func() *BinaryUpdate
// Llama is Pi's built-in llama.cpp provider: /llama manages its router
// models, /login configures it, and startup refreshes its catalog.
Llama *llama.Host
// OfflineMode skips startup network catalog refreshes, like PI_OFFLINE.
OfflineMode bool
// ResourceSourceInfoProvider returns source metadata for currently known
// prompts/skills/extensions/themes, keyed by absolute path. Used to enrich
// verbose startup output and /reload diagnostics with package origin.
// Mirrors upstream resource-loader.ts PathMetadata/SourceInfo plumbing.
ResourceSourceInfoProvider func() map[string]ResourceSourceInfo
// ReloadResourceProvider recomputes settings-backed prompt/theme/skill/
// context-file inputs on /reload so the interactive session mirrors
// upstream resourceLoader.reload() instead of reusing startup snapshots.
ReloadResourceProvider func() ReloadResourceSnapshot
// Verbose forces verbose startup output (overrides quietStartup).
// Mirrors upstream InteractiveOptions.verbose (interactive-mode.ts:184).
Verbose bool
// Skills is the loaded set of skill definitions, used to expand
// /skill:name commands in user prompts.
// Mirrors upstream resourceLoader.getSkills() (agent-session.ts:1124-1151).
Skills []*SkillDef
// RebuildSystemPrompt reconstructs the base system prompt + structured
// prompt options after /reload from the current skills/context files.
// Mirrors upstream session.reload() → _rebuildSystemPrompt.
RebuildSystemPrompt func(skills []*SkillDef, contextFiles []ContextFile) (string, extension.BuildSystemPromptOptions)
// BridgeExtensionTools converts registered extension tools into
// agent.AgentTool values so /reload can refresh the live tool registry.
BridgeExtensionTools func([]extension.RegisteredTool) ([]agent.AgentTool, []error)
// SkillPaths are the source paths from which Skills were loaded.
// Used by /reload to re-discover skills from disk. If empty, skills
// are not reloaded (only the initial set from startup is used).
SkillPaths []string
// NoSkills disables skill loading and reload.
NoSkills bool
// ContextFiles lists the loaded AGENTS.md/CLAUDE.md project context files.
// Shown in the startup banner when verbose/non-quiet. Mirrors upstream
// showLoadedResources [Context] section (interactive-mode.ts:1303-1317).
ContextFiles []ContextFile
// ThinkingLevel is the initial thinking level override from --thinking.
// Empty means use default (settings or "medium"). Mirrors upstream
// interactiveOptions.thinking (interactive-mode.ts:186).
ThinkingLevel string
// SubprocessUIBridge, when non-nil, is the UI bridge for subprocess
// extensions. Run() wires it to the TUI after creation via
// SetUIContext and SetInvalidate.
//
// pig-specific: no upstream equivalent.
SubprocessUIBridge SubprocessUIBridge
// SubprocessHost, when non-nil, manages subprocess extension lifecycle.
// Used by /reload to rebuild and re-spawn changed extensions.
//
// pig-specific: no upstream equivalent.
SubprocessHost SubprocessHost
// StageExtensionSDKs, when non-nil, materializes the SDKs this binary
// embeds before /reload recompiles out-of-tree extensions, and prunes
// builds whose fingerprint proves they came from an older SDK.
//
// Injected so this package does not depend on the SDK bundle implementation
// and so a test can observe that reload stages before it rebuilds.
//
// pig-specific: no upstream equivalent, because upstream extensions are
// in-process TypeScript and there is no SDK to stage.
StageExtensionSDKs func() error
// BuiltinExtensions contains generic in-process runtime extensions, such as
// Piglet capability scoping, in configured load order after subprocess
// extensions.
BuiltinExtensions []extension.Extension
// ReloadBuiltinExtensions reconstructs BuiltinExtensions for /reload. A
// factory callback is required because copying an Extension would retain the
// handler closures and state that upstream discards on reload.
ReloadBuiltinExtensions func() []extension.Extension
// NoModelWarning, when non-empty, is rendered as a yellow warning
// line immediately before the welcome banner. Mirrors upstream
// reportDiagnostics("Warning: No models available. ...") which the
// pi TUI prints when the user starts without `--model` and has no
// detectable credentials.
NoModelWarning string
// StartupDiagnostics are shown in the chat after the welcome banner.
// Mirrors upstream InteractiveModeOptions.startupDiagnostics.
StartupDiagnostics []AgentSessionRuntimeDiagnostic
// StartupMark, when non-nil, is called at key phases during Run()
// for startup timing. See cmd/pig/startup_trace.go.
StartupMark func(label string)
// LoginHeaderOptions contains host-owned operational text and terminal
// rendering capabilities for an extension-provided login.
LoginHeaderOptions LoginHeaderOptions
// BuiltInHeaderLines are the stock text header restored when an extension
// clears its custom header.
BuiltInHeaderLines []string
// LoginVisible applies the startup silence gate to built-in and native
// extension login presentations.
LoginVisible bool
}
InteractiveOptions configures the interactive mode.
type InteractiveSessionHandle ¶
type InteractiveSessionHandle interface {
// Agent returns the underlying agent loop.
Agent() *agent.Agent
// Inner returns the on-disk session. The local-package type
// reference (*Session) is the same as *icodingagent.Session
// from coding/'s point of view.
Inner() *Session
// Events returns the agent's streaming event channel. Used by
// processAgentEvents to drive live UI updates.
Events() <-chan agent.AgentEvent
// SetModel swaps the active LLM model mid-session and persists a
// model_change audit entry.
SetModel(*ai.Model, ...ModelMutationOptions) error
// SetThinkingLevel applies and records reasoning without changing defaults unless Persist is set.
SetThinkingLevel(ai.ThinkingLevel, ...ModelMutationOptions) error
// StreamModel starts a mode-independent model operation through the
// Session-owned runtime.
StreamModel(context.Context, *ai.Model, ai.Context, ai.StreamOptions) *ai.AssistantMessageEventStream
// AbortCompaction cancels an in-flight Compact() call. Safe to
// call when no compaction is running (no-op).
// Mirrors upstream AgentSession.abortCompaction().
AbortCompaction()
// CheckPromptCompaction runs prompt()'s compaction check before a new
// user message starts a run.
CheckPromptCompaction(ctx context.Context) error
// RunAgentPrompt runs one agent run to settlement like Pi's
// _runAgentPrompt: start seeds it, then automatic retry, overflow and
// length recovery, threshold compaction, and queued input continue it
// until nothing asks for another run or ctx is cancelled. The Events
// consumer must acknowledge the barriers it waits on (see eventBarrier).
RunAgentPrompt(ctx context.Context, start func(context.Context) ([]agent.AgentMessage, error)) ([]agent.AgentMessage, error)
// RunInputHandlers runs the extension input handlers for user input
// (upstream _runInputHandlers); behavior reaches them only while a run
// is active.
RunInputHandlers(ctx context.Context, text string, images []ai.ImageContent, source extension.InputSource, behavior string) (string, []ai.ImageContent, bool, error)
// AbortRetry cancels a pending automatic-retry delay without aborting
// the run. Mirrors upstream AgentSession.abortRetry().
AbortRetry()
// AbortBranchSummary cancels an in-flight branch summarization. Safe
// to call when no summarization is running (no-op).
// Mirrors upstream AgentSession.abortBranchSummary().
AbortBranchSummary()
// ReplaceInner swaps the underlying on-disk session. Used by /resume
// to point the SessionHandle at a newly loaded session so tree
// navigation and compaction operate on the correct entries.
ReplaceInner(sess *Session)
// summarization. Returns NavigateTreeResult.
// Mirrors upstream AgentSession.navigateTree().
NavigateTreeHandle(ctx context.Context, targetID string, summarize bool, customInstructions string) (NavigateTreeResult, error)
// CacheWarmingStatus reports the Session's cache warmer, or nil when it
// has none. Mirrors upstream AgentSession.cacheWarmingStatus.
CacheWarmingStatus() *CacheWarmingStatus
// SetCacheWarmingMode persists the mode and reconciles active warming.
// Mirrors upstream AgentSession.setCacheWarmingMode.
SetCacheWarmingMode(CacheWarmingMode) error
// OnAgentSettled tells the cache warmer that an agent run settled.
OnAgentSettled()
}
InteractiveSessionHandle is the contract InteractiveMode uses to access a pre-constructed coding session. *coding.Session in the public SDK package satisfies this: its Agent() and Inner() methods have the matching signatures.
We use an interface (rather than importing coding/.Session directly) to break the import cycle: coding/ already imports internal/codingagent for its on-disk Session type, so internal/codingagent cannot import coding/.
main.go (which imports both packages) does the bridging:
sess, _ := coding.NewSession(svcs, opts)
m := codingagent.NewInteractiveMode(codingagent.InteractiveOptions{
SessionHandle: sess, // *coding.Session implements this interface
...
})
type KeybindingConflict ¶
type KeybindingDefinition ¶
type KeybindingsManager ¶
type KeybindingsManager struct {
// contains filtered or unexported fields
}
func DefaultKeybindingsManager ¶
func DefaultKeybindingsManager() *KeybindingsManager
func NewKeybindingsManager ¶
func NewKeybindingsManager(agentDir string) *KeybindingsManager
func (*KeybindingsManager) Conflicts ¶
func (km *KeybindingsManager) Conflicts() []KeybindingConflict
func (*KeybindingsManager) DisplayFor ¶
func (km *KeybindingsManager) DisplayFor(action string) string
DisplayFor returns a human-readable key hint for the first binding of the given action (e.g. "Alt+Up"). Returns the raw KeyID if no display mapping exists.
func (*KeybindingsManager) Get ¶
func (km *KeybindingsManager) Get(action string) []KeyID
func (*KeybindingsManager) HotkeyLines ¶
func (km *KeybindingsManager) HotkeyLines() []string
func (*KeybindingsManager) KeyText ¶
func (km *KeybindingsManager) KeyText(action string) string
KeyText returns the un-capitalized display text for every key bound to action, joined by "/", mirroring upstream keyText (keybinding-hints.ts): getKeys → formatKeyText without capitalization. Used for the startup keybinding hints.
func (*KeybindingsManager) Matches ¶
func (km *KeybindingsManager) Matches(input, action string) bool
func (*KeybindingsManager) MatchesEditorHistory ¶
func (km *KeybindingsManager) MatchesEditorHistory(input string) bool
MatchesEditorHistory reports whether input matches an explicit tui.editor.historyPrevious or historyNext binding. The focused editor gives those precedence over app actions (custom-editor.ts handleInput), so a user can bind ctrl+p to history although it cycles models by default.
func (*KeybindingsManager) Reload ¶
func (km *KeybindingsManager) Reload() error
func (*KeybindingsManager) Resolve ¶
func (km *KeybindingsManager) Resolve(input string) string
func (*KeybindingsManager) ResolvedBindings ¶
func (km *KeybindingsManager) ResolvedBindings() map[string][]string
ResolvedBindings returns a detached snapshot of every canonical action's resolved key IDs for extension-shortcut conflict checks.
func (*KeybindingsManager) Save ¶
func (km *KeybindingsManager) Save(path string) error
func (*KeybindingsManager) SetUserBindings ¶
func (km *KeybindingsManager) SetUserBindings(bindings map[string][]KeyID)
type LabelEntry ¶
type LabelEntry struct {
SessionEntryBase
TargetID string `json:"targetId"`
Label *string `json:"label"`
}
LabelEntry is upstream's "user-renamed this branch" marker. Carries nil Label to delete a previously-set label.
type LoadPromptTemplatesResult ¶
type LoadPromptTemplatesResult struct {
Templates []PromptTemplate
Diagnostics []extension.ResourceDiagnostic
}
LoadPromptTemplatesResult carries loaded commands and file-read or YAML warnings.
func LoadPromptTemplates ¶
func LoadPromptTemplates(cwd, agentDir string, extraPaths ...string) LoadPromptTemplatesResult
LoadPromptTemplates loads user, project, and explicit prompt paths.
type LoginHeaderOptions ¶
type LoginHeaderOptions struct {
OperationalLines []string
TrueColor bool
GlyphFree bool
ColorOverrides map[byte]color.RGBA
}
LoginHeaderOptions contains host-owned values used by the native login template. OperationalLines are rendered after the extension-owned identity.
type MarkdownSettings ¶
type MarkdownSettings struct {
CodeBlockIndent string `json:"codeBlockIndent,omitempty"`
Mermaid string `json:"mermaid,omitempty"`
}
MarkdownSettings mirrors upstream MarkdownSettings. Mirrors upstream settings-manager.ts MarkdownSettings.
type MessageEntry ¶
type MessageEntry struct {
SessionEntryBase
Message agent.AgentMessage `json:"message"`
}
type ModelChangeEntry ¶
type ModelChangeEntry struct {
SessionEntryBase
Provider string `json:"provider"`
ModelID string `json:"modelId"`
}
type ModelEntry ¶
type ModelEntry struct {
ProviderID string
ModelID string
APIKey string
BaseURL string
DisplayName string
API string // "openai-completions" | "anthropic-messages" | etc.
Headers map[string]string // resolved request headers from provider/model configuration
ModelHeaders map[string]string // intrinsic public Model.headers from the generated catalog
AuthHeader bool // put API key in Authorization header (for custom providers)
Compat *ai.OpenAICompat // compat flags for OpenAI-compatible providers
Reasoning bool // whether the model supports reasoning/thinking
ThinkingLevelMap ai.ThinkingLevelMap
SamplingParams map[string]any
InputLimits *ai.ModelInputLimits
Input []string // ["text"] or ["text","image"]
ContextWindow int // default: 128000
MaxTokens int // default: 16384
InputCost float64
OutputCost float64
CacheReadCost float64
CacheWriteCost float64
CostTiers []ai.CostTier
PromptCache ai.ModelPromptCache
Env map[string]string // provider-scoped env overrides (auth.json env)
Insecure bool // skip TLS verification (self-signed/internal-CA on-prem endpoints)
}
ModelEntry holds the resolved configuration for a single provider+model. Produced by ModelRegistry.Resolve from the upstream models.json schema.
type ModelMutationOptions ¶
type ModelMutationOptions struct {
Persist bool
}
ModelMutationOptions controls whether a Session mutation also saves a global default.
type ModelOperationBindings ¶
type ModelOperationBindings struct {
CurrentModel func() *ai.Model
ModelLookup func(providerID, modelID string) *ai.Model
ModelCatalog func() []*ai.Model
Registry *ModelRegistry
ModelBuilder func(spec string) (*ai.Model, error)
SessionHandle InteractiveSessionHandle
Thinking ai.ThinkingLevel
Transport ai.Transport
}
type ModelOperationBridge ¶
type ModelRegistry ¶
type ModelRegistry struct {
// contains filtered or unexported fields
}
ModelRegistry resolves model configurations from models.json and environment. Mirrors upstream model-registry.ts.
func NewModelRegistry ¶
func NewModelRegistry(agentDir string) *ModelRegistry
NewModelRegistry creates a registry, loading from <agent-dir>/models.json if present.
func (*ModelRegistry) AvailableProviderCount ¶
func (r *ModelRegistry) AvailableProviderCount() int
AvailableProviderCount returns the number of distinct providers with configured auth. Used by the footer to decide whether to show the provider chip. Mirrors upstream updateAvailableProviderCount (interactive-mode.ts:3858-3862).
func (*ModelRegistry) BugReportProviderInfo ¶
func (r *ModelRegistry) BugReportProviderInfo(providerID string) *BugReportProvider
BugReportProviderInfo describes providerID from models.json and extension registrations. It returns nil when the registry is nil.
func (*ModelRegistry) GetAll ¶
func (r *ModelRegistry) GetAll() []ModelEntry
GetAll returns explicit models and configured overlays for exact generated identities; dynamic providers take precedence over models.json.
func (*ModelRegistry) GetAvailable ¶
func (r *ModelRegistry) GetAvailable() []ModelEntry
GetAvailable returns all model entries from dynamic (extension-registered) and models.json providers that have configured auth (API key or OAuth credentials). Mirrors upstream ModelRegistry.getAvailable() (model-registry.ts:2266), which filters a single #models list merged from built-ins, models.json custom overlays, and runtime extension overlays -- not just extension-registered providers. A provider name registered dynamically takes precedence over a models.json entry of the same name, matching Resolve()'s lookup order.
func (*ModelRegistry) GetProviderAuthStatus ¶
func (r *ModelRegistry) GetProviderAuthStatus(providerID string) ai.AuthStatus
func (*ModelRegistry) GetProviderDisplayName ¶
func (r *ModelRegistry) GetProviderDisplayName(providerID string) string
func (*ModelRegistry) HasAnyKey ¶
func (r *ModelRegistry) HasAnyKey(providerID string) bool
HasAnyKey reports whether the registry has at least one entry for the given provider with a non-empty (post-resolve) APIKey, or the environment configures its auth.
func (*ModelRegistry) HasConfiguredAuth ¶
func (r *ModelRegistry) HasConfiguredAuth(providerID string) bool
HasConfiguredAuth reports whether the provider has either an API key (from env, models.json, or dynamic registration) or stored OAuth credentials. Mirrors upstream ModelRegistry.hasConfiguredAuth() (model-registry.ts:605-612).
func (*ModelRegistry) HasGeneratedModel ¶
func (r *ModelRegistry) HasGeneratedModel(providerID, modelID string) bool
HasGeneratedModel reports whether provider composition retains one generated identity.
func (*ModelRegistry) HasModelDefinition ¶
func (r *ModelRegistry) HasModelDefinition(providerID, modelID string) bool
HasModelDefinition reports whether provider composition exposes providerID/modelID through an explicit models list.
func (*ModelRegistry) LoadError ¶
func (r *ModelRegistry) LoadError() string
LoadError returns any error from parsing models.json.
func (*ModelRegistry) RadiusAPIKey ¶
RadiusAPIKey resolves the request credential of a Radius provider: a runtime key, a stored OAuth token (refreshed when expired) or API key, then RADIUS_API_KEY.
func (*ModelRegistry) RadiusOAuth ¶
func (r *ModelRegistry) RadiusOAuth(providerID string) (*ai.RadiusOAuth, bool)
RadiusOAuth returns the OAuth flow of the Radius provider providerID.
func (*ModelRegistry) RadiusOAuthFlows ¶
func (r *ModelRegistry) RadiusOAuthFlows() []*ai.RadiusOAuth
RadiusOAuthFlows returns every configured Radius OAuth flow, sorted by ID.
func (*ModelRegistry) Refresh ¶
func (r *ModelRegistry) Refresh()
Refresh reloads models.json from disk, preserves dynamic provider registrations, and restores stored dynamic catalogs without network access.
func (*ModelRegistry) RefreshCatalogs ¶
func (r *ModelRegistry) RefreshCatalogs(ctx context.Context, options CatalogRefreshOptions) CatalogRefreshResult
RefreshCatalogs mirrors ModelRuntime.refresh for dynamic providers: each selected provider restores its stored catalog and, when allowed, refreshes it from the network. A newer refresh of the same provider supersedes an older one. Errors of cancelled or superseded refreshes are not reported.
func (*ModelRegistry) RegisterProvider ¶
func (r *ModelRegistry) RegisterProvider(name string, configMap extension.ProviderConfig)
RegisterProvider registers or overrides a provider at runtime.
func (*ModelRegistry) RemoveRuntimeAPIKey ¶
func (r *ModelRegistry) RemoveRuntimeAPIKey(providerID string)
RemoveRuntimeAPIKey drops providerID's runtime key. Mirrors upstream ModelRuntime.removeRuntimeApiKey.
func (*ModelRegistry) Resolve ¶
func (r *ModelRegistry) Resolve(providerID, modelID string) (ModelEntry, bool)
Resolve returns a ModelEntry for the given provider+model combination. Resolution order:
- Custom model definition in models.json (provider → models[])
- Model override in models.json (provider → modelOverrides[modelID])
- Provider-level defaults from models.json (baseUrl, apiKey, compat, headers)
- Environment variables (PROVIDER_API_KEY)
Mirrors upstream parseModels + request-auth resolution.
func (*ModelRegistry) ResolveGeneratedModel ¶
func (r *ModelRegistry) ResolveGeneratedModel(providerID, modelID string, generated *ai.GeneratedModel) ModelEntry
ResolveGeneratedModel layers provider configuration and a matching model override onto one generated model.
func (*ModelRegistry) RuntimeAPIKey ¶
func (r *ModelRegistry) RuntimeAPIKey(providerID string) (string, bool)
RuntimeAPIKey returns the non-persistent API key set for providerID.
func (*ModelRegistry) RuntimeModels ¶
func (r *ModelRegistry) RuntimeModels() []RuntimeModel
RuntimeModels returns the composed model identities in upstream ModelRuntime.getModels order: built-in providers first, then models.json providers in file order, then extension-registered providers. Within a provider, the catalog models come first and models.json or extension definitions replace a catalog model of the same id or follow in definition order. An extension provider that declares models replaces the catalog.
func (*ModelRegistry) SetAuthStorage ¶
func (r *ModelRegistry) SetAuthStorage(auth *ai.AuthStorage)
SetAuthStorage wires the credential store for auth-aware filtering. Must be called before GetAvailable or HasConfiguredAuth produce meaningful results. Mirrors upstream ModelRegistry constructor receiving authStorage (model-registry.ts:318).
func (*ModelRegistry) SetChangeListener ¶
func (r *ModelRegistry) SetChangeListener(notify func()) func()
SetChangeListener replaces the callback invoked after a committed registry change and returns a draining detach function.
func (*ModelRegistry) SetModelsStore ¶
func (r *ModelRegistry) SetModelsStore(store ai.ModelsStore)
SetModelsStore replaces the dynamic catalog store.
func (*ModelRegistry) SetProvider ¶
func (r *ModelRegistry) SetProvider(name string, configMap extension.ProviderConfig)
SetProvider replaces a runtime-registered provider in one committed change, so fields absent from config are cleared rather than kept. The built-in llama.cpp provider republishes its resolved auth and catalog this way.
func (*ModelRegistry) SetRuntimeAPIKey ¶
func (r *ModelRegistry) SetRuntimeAPIKey(providerID, apiKey string)
SetRuntimeAPIKey installs a non-persistent API key for providerID. It acts as a stored api_key credential that is never written to auth.json. Mirrors upstream ModelRuntime.setRuntimeApiKey over RuntimeCredentials.
func (*ModelRegistry) UnregisterProvider ¶
func (r *ModelRegistry) UnregisterProvider(name string)
UnregisterProvider removes a runtime-registered provider.
type NavigateTreeResult ¶
type NavigateTreeResult struct {
}
NavigateTreeResult is the TUI-facing result of a tree navigation operation. Re-exported here (from coding.NavigateTreeResult) so slash handlers don't need to import the public SDK package (cycle prevention).
type NoopUI ¶
type NoopUI struct{}
NoopUI is a non-interactive ExtensionUIContext for headless mode.
type PackageManagerOwner ¶
type PackageManagerOwner string
PackageManagerOwner names a package manager proven to own an installation.
type PackageSource ¶
type PackageSource struct {
Source string `json:"source,omitempty"`
Extensions []string `json:"extensions,omitempty"`
Skills []string `json:"skills,omitempty"`
Prompts []string `json:"prompts,omitempty"`
Themes []string `json:"themes,omitempty"`
// WasObject tracks whether the JSON was an object (vs bare string).
// Upstream considers ANY object-format package as "filtered"
// (typeof pkg === "object"), even if no filter fields are set.
WasObject bool `json:"-"`
}
PackageSource mirrors upstream settings-manager.ts PackageSource. JSON accepts either a bare string source or an object with resource filters.
func (PackageSource) Filtered ¶
func (p PackageSource) Filtered() bool
Filtered reports whether the package was specified in object form. Upstream: `filtered: typeof pkg === "object"`: any object form is filtered. For programmatically constructed sources, filter fields also signal filtering.
func (PackageSource) MarshalJSON ¶
func (p PackageSource) MarshalJSON() ([]byte, error)
MarshalJSON preserves upstream's string-or-object wire shape.
func (*PackageSource) UnmarshalJSON ¶
func (p *PackageSource) UnmarshalJSON(data []byte) error
UnmarshalJSON preserves upstream's string-or-object wire shape.
type ParsedSkillBlockFromText ¶
type ParsedSkillBlockFromText struct {
Name string
Location string
Content string
UserMessage string // trailing user text after </skill>\n\n, or ""
}
ParsedSkillBlockFromText holds the parsed skill invocation data extracted from a user message text. Mirrors upstream's ParsedSkillBlock return value from agent-session.ts:parseSkillBlock.
func ParseSkillBlock ¶
func ParseSkillBlock(text string) *ParsedSkillBlockFromText
ParseSkillBlock attempts to parse a skill XML block from message text. Returns nil if the text doesn't match the skill block format. Mirrors upstream parseSkillBlock (agent-session.ts:102-116).
type ProcessedCLIArgs ¶
type ProcessedCLIArgs struct {
Text string
Images []ai.ImageContent
}
ProcessedCLIArgs is the upstream-shaped result of processing CLI @file arguments: text placeholders plus image attachments.
func ProcessCLIFileArguments ¶
func ProcessCLIFileArguments(fileArgs []string, cwd string) (ProcessedCLIArgs, error)
ProcessCLIFileArguments expands CLI @file arguments into the upstream initial-message payload. Text files are wrapped as <file name="/abs/path">\ncontent\n</file>\n. Image files are attached as ai.ImageContent blocks and represented in the text stream as either an empty <file> tag (no resize needed) or a dimension note when resized.
type ProjectTrustOption ¶
type ProjectTrustOption struct {
Label string
Trusted bool
Updates []ProjectTrustUpdate
SavedPath string
}
ProjectTrustOption is one row in a project-trust selector.
func GetProjectTrustOptions ¶
func GetProjectTrustOptions(cwd string, includeSessionOnly bool) []ProjectTrustOption
GetProjectTrustOptions builds the upstream-ordered selector choices.
type ProjectTrustStore ¶
type ProjectTrustStore struct {
// contains filtered or unexported fields
}
ProjectTrustStore reads and writes <agentDir>/trust.json.
func NewProjectTrustStore ¶
func NewProjectTrustStore(agentDir string) *ProjectTrustStore
NewProjectTrustStore opens the store rooted at agentDir.
func (*ProjectTrustStore) Get ¶
func (s *ProjectTrustStore) Get(cwd string) (*bool, error)
Get returns the nearest decision for cwd, or nil when none applies.
func (*ProjectTrustStore) GetEntry ¶
func (s *ProjectTrustStore) GetEntry(cwd string) (entry *ProjectTrustStoreEntry, err error)
GetEntry returns the nearest stored decision, walking through parent paths.
func (*ProjectTrustStore) Set ¶
func (s *ProjectTrustStore) Set(cwd string, decision *bool) error
Set sets or clears the canonical decision for cwd.
func (*ProjectTrustStore) SetMany ¶
func (s *ProjectTrustStore) SetMany(updates []ProjectTrustUpdate) error
SetMany applies one locked read-modify-write batch. A nil decision deletes that key; unrelated null entries already present in the store are preserved.
type ProjectTrustStoreEntry ¶
ProjectTrustStoreEntry is the nearest stored decision for a cwd.
type ProjectTrustUpdate ¶
ProjectTrustUpdate sets (true/false) or clears (nil) a path's decision.
type ProjectedSessionEntry ¶
type ProjectedSessionEntry struct {
SourceEntry SessionEntry
Messages []agent.AgentMessage
}
ProjectedSessionEntry pairs a raw append-only entry with the model-visible messages it contributes after context edits (session-manager.ts ProjectedSessionEntry). Messages is empty for state-only entries and omissions.
type PromptTemplate ¶
type PromptTemplate struct {
Name string // basename without .md
Description string // from frontmatter, or first non-empty body line truncated to 60
ArgumentHint string // from frontmatter `argument-hint`, optional
Content string // body (without frontmatter)
FilePath string // absolute path on disk
Scope string // "user" | "project" | "external"
}
PromptTemplate is one loaded `.md` file.
type ProviderRetryConfig ¶
ProviderRetryConfig holds resolved provider/SDK retry settings.
type ProviderRetrySettings ¶
type ProviderRetrySettings struct {
TimeoutMs *int `json:"timeoutMs,omitempty"`
MaxRetries *int `json:"maxRetries,omitempty"`
// MaxRetryDelayMs is a pointer so an explicit 0 (upstream disables the cap:
// provider-retry.ts "set it to zero to disable the limit") is distinguishable
// from unset (nil -> 60s default). A plain int cannot tell 0 from absent.
MaxRetryDelayMs *int `json:"maxRetryDelayMs,omitempty"`
}
ProviderRetrySettings mirrors upstream retry.provider settings. Used for provider/SDK-level request retries and deadlines.
type ReloadCellDiag ¶
type ReloadCellDiag struct {
Key string
Strategy string
Language string
Extensions []string
Hash string
BinaryPath string
Cached bool
BuildDuration time.Duration
Replaced bool
Quarantined bool
Reason string
}
ReloadCellDiag is a UI-safe copy of subprocess.ReloadCellReport. It is duplicated here so internal/codingagent can render /reload --explain without importing the subprocess host package directly.
type ReloadDiag ¶
type ReloadDiag struct {
ContextFiles int
Skills int
Prompts int
Extensions int
Themes int
// Diagnostics is one human-readable line per warning/error gathered
// during reload. Mirrors upstream's `[Extension issues]`,
// `[Skill conflicts]`, `[Prompt conflicts]` sections.
Diagnostics []string
// Cells is the placement summary produced by the subprocess host. Empty
// when no subprocess host is active (e.g. headless commands).
// pig-specific. Used by /reload --explain.
Cells []ReloadCellDiag
// ReloadDuration is the wall time spent in subprocess Reload(). Zero when
// the host is not active.
ReloadDuration time.Duration
}
ReloadDiag holds resource counts and diagnostic warnings surfaced by /reload. Mirrors the information upstream showLoadedResources collects (interactive-mode.ts:1231-1410). Counts are always populated; the Diagnostics slice carries one human-readable warning line per conflict (commands, shortcuts, extension load errors).
type ReloadResourceSnapshot ¶
type ReloadResourceSnapshot struct {
PromptPaths []string
ThemePaths []string
SkillPaths []string
ContextFiles []ContextFile
ResourceSourceInfo map[string]ResourceSourceInfo
}
ReloadResourceSnapshot is the recomputed settings/resource view used by /reload. It mirrors the upstream resource-loader/session.reload flow where prompt/theme/skill/context inputs are re-resolved from current settings.
type RequestAuthRuntime ¶
type RequestAuthRuntime struct {
// contains filtered or unexported fields
}
RequestAuthRuntime resolves provider credentials the way upstream ModelRuntime does for request auth.
func NewRequestAuthRuntime ¶
func NewRequestAuthRuntime(ctx context.Context, options RequestAuthRuntimeOptions) (*RequestAuthRuntime, error)
NewRequestAuthRuntime composes built-in providers with models.json.
func (*RequestAuthRuntime) CheckAuth ¶
func (r *RequestAuthRuntime) CheckAuth(ctx context.Context, providerID string) (*ai.AuthCheck, error)
CheckAuth reports configured auth for a provider without refreshing OAuth.
func (*RequestAuthRuntime) GetAuth ¶
func (r *RequestAuthRuntime) GetAuth(ctx context.Context, providerID string, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
GetAuth resolves request auth for a provider, refreshing and persisting OAuth credentials that are about to expire.
func (*RequestAuthRuntime) GetError ¶
func (r *RequestAuthRuntime) GetError() string
GetError reports models.json, composition, and availability errors.
func (*RequestAuthRuntime) GetModelAuth ¶
func (r *RequestAuthRuntime) GetModelAuth(ctx context.Context, model RuntimeModel, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
GetModelAuth resolves request auth for a model: provider auth plus the model's intrinsic and configured headers.
func (*RequestAuthRuntime) GetModels ¶
func (r *RequestAuthRuntime) GetModels(providerID string) []RuntimeModel
GetModels returns every provider's models, or one provider's when providerID is non-empty.
func (*RequestAuthRuntime) GetProvider ¶
func (r *RequestAuthRuntime) GetProvider(providerID string) *RuntimeProvider
GetProvider returns a composed provider by exact id, or nil.
func (*RequestAuthRuntime) GetProviders ¶
func (r *RequestAuthRuntime) GetProviders() []*RuntimeProvider
GetProviders returns composed providers in registration order.
func (*RequestAuthRuntime) HasConfiguredAuth ¶
func (r *RequestAuthRuntime) HasConfiguredAuth(providerID string) bool
HasConfiguredAuth reports the provider's availability from the last refresh.
func (*RequestAuthRuntime) ListCredentials ¶
func (r *RequestAuthRuntime) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
ListCredentials lists stored credential metadata.
func (*RequestAuthRuntime) Refresh ¶
func (r *RequestAuthRuntime) Refresh(ctx context.Context)
Refresh restores dynamic catalogs from the models store without network access, then recomputes configured-provider availability. An availability failure keeps the previous availability and is reported through GetError.
type RequestAuthRuntimeOptions ¶
type RequestAuthRuntimeOptions struct {
Credentials ai.CredentialStore
// AgentDir holds models.json; empty means no models.json, as upstream
// modelsPath null.
AgentDir string
// RefreshOnCreate computes configured-provider availability at creation.
RefreshOnCreate bool
// AuthContext overrides the process environment and filesystem.
AuthContext *ai.AuthContext
// ModelsStore holds refreshed dynamic catalogs; nil means
// <AgentDir>/models-store.json, or an in-memory store without AgentDir.
ModelsStore ai.ModelsStore
}
RequestAuthRuntimeOptions mirrors the CreateModelRuntimeOptions this surface honours.
type ResolvedPath ¶
ResolvedPath pairs a candidate input path with the canonical path it resolves to via filepath.EvalSymlinks. Returned by DedupBySymlink.
func DedupBySymlink ¶
func DedupBySymlink(paths []string) []ResolvedPath
DedupBySymlink walks the input paths, resolves each via filepath.EvalSymlinks, and returns one entry per distinct canonical path (in input order). Duplicates produced by symlinks pointing at the same target are silently dropped.
On EvalSymlinks error (broken symlink, permission denied, loop), the raw path is treated as its own canonical and kept. This mirrors upstream package-manager.ts:2280-2320 which falls back to the raw path on realpathSync failure (try/catch).
Loop guard: filepath.EvalSymlinks already returns an error after Go's internal max-link traversal limit, so we just trust the stdlib.
Reference: .upstream/current/packages/coding-agent/src/core/package-manager.ts
type ResourceSourceInfo ¶
type ResourceSourceInfo struct {
Path string
ResourceType string // "extensions" | "skills" | "prompts" | "themes"
Enabled bool
Scope string // "user" | "project"
Origin string // "package" | "top-level"
Source string // package source string or "local"
BaseDir string // package root for package-relative shortening
}
ResourceSourceInfo tracks where a loaded resource came from. Mirrors upstream PathMetadata / SourceInfo flow used by resource-loader.ts and interactive-mode.ts to annotate startup context and collision diagnostics with package origin + scope.
func (ResourceSourceInfo) DisplayName ¶
func (i ResourceSourceInfo) DisplayName() string
DisplayName derives the logical resource name used for collision grouping.
type RetryConfig ¶
RetryConfig holds resolved retry settings with defaults applied.
type RetrySettingsJSON ¶
type RetrySettingsJSON struct {
Enabled *bool `json:"enabled,omitempty"`
// MaxRetries and BaseDelayMs are pointers so an explicit 0 is kept, as
// upstream's `?? default` does.
MaxRetries *int `json:"maxRetries,omitempty"`
BaseDelayMs *int `json:"baseDelayMs,omitempty"`
// MaxAgentDelayMs caps each agent-level retry delay (default 60000).
MaxAgentDelayMs *int `json:"maxAgentDelayMs,omitempty"`
Provider *ProviderRetrySettings `json:"provider,omitempty"`
}
RetrySettingsJSON mirrors upstream Settings.retry JSON shape (settings-manager.ts:682-690). Defaults: enabled=true, maxRetries=3, baseDelayMs=2000.
type RuntimeModel ¶
type RuntimeModel struct {
Provider string
ID string
Name string
// Headers are the model's intrinsic catalog headers.
Headers ai.ProviderHeaders
}
RuntimeModel is the model identity request-auth resolution needs from upstream Model<Api>.
type RuntimeProvider ¶
type RuntimeProvider struct {
ID string
Auth ai.ProviderAuth
// contains filtered or unexported fields
}
RuntimeProvider is a composed provider: its id and auth methods. Mirrors the auth-bearing part of upstream Provider.
type SelfUpdateActionResult ¶
SelfUpdateActionResult is the outcome of attempting one tier's update. The caller surfaces Action and Message verbatim; Done marks a successful mutation. Cause carries the originating error so the caller can distinguish a benign "up to date" from a real failure.
func ApplySelfUpdateTier ¶
func ApplySelfUpdateTier( applyStandalone func(exePath string) error, applyPackageManager func(prov *SelfUpdateProvenance) error, ) SelfUpdateActionResult
ApplySelfUpdateTier resolves exactly one installation tier and applies its update, surfacing any failure from the started tier without falling through. The standalone download/replace path is supplied via applyStandalone so the cmd layer keeps ownership of the HTTP client, manifest, and version compare.
type SelfUpdateCommand ¶
type SelfUpdateCommand struct {
Command string
Args []string
Display string
// Steps holds an optional ordered list of commands to run in sequence.
// Mirrors upstream SelfUpdateCommand.steps (config.ts v0.73.1).
Steps []*SelfUpdateCommand
}
SelfUpdateCommand describes the command a managed install would run to update itself. pig returns nil because it ships as a standalone binary, not a global npm/pnpm/yarn package.
Mirrors upstream SelfUpdateCommand (config.ts). Steps holds an optional sequence of sub-commands (e.g. uninstall old name, then install new name).
func GetSelfUpdateCommand ¶
func GetSelfUpdateCommand(_ string, _ []string, _ ...string) *SelfUpdateCommand
GetSelfUpdateCommand returns nil without a resolved provenance and exact release. The self-update tier resolver supplies those facts before invoking PackageManagerUpdateCommand; this generic path must not invent an unpinned package-manager mutation.
updatePackageName is the new package name when renaming a package during update (mirrors upstream getSelfUpdateCommand updatePackageName param, v0.73.1).
func PackageManagerUpdateCommand ¶
func PackageManagerUpdateCommand(owner PackageManagerOwner, installedPackage string, npmCommand []string, target SelfUpdatePackageTarget) *SelfUpdateCommand
PackageManagerUpdateCommand returns the exact command the owning manager runs to update its installation. Mirrors upstream getSelfUpdateCommandForMethod command construction including --ignore-scripts. The owner: proven by tier resolution: drives the command name; npmCommand supplies optional extra args (e.g. a configured registry) for the npm owner only. Returns nil for an unknown owner.
type SelfUpdatePackageTarget ¶
SelfUpdatePackageTarget is the package a self-update installs: its name, and the spec the package manager installs, which is the name when empty. Mirrors upstream SelfUpdatePackageTarget (config.ts).
type SelfUpdateProvenance ¶
type SelfUpdateProvenance struct {
Tier SelfUpdateTier
ExePath string
PackageOwner PackageManagerOwner
// PackageName is the owning package spec when Tier == tierPackageManager.
PackageName string
}
SelfUpdateProvenance is the resolved ownership of the running executable. Exactly one Tier is set; ambiguity is reported as an error rather than a mixed tier.
func ResolveSelfUpdateTier ¶
func ResolveSelfUpdateTier() (*SelfUpdateProvenance, error)
ResolveSelfUpdateTier proves exactly one installation owner for the running executable before any mutation. It never mutates state. Ambiguous ownership returns a *TierError and the caller must refuse to update.
Resolution order follows the tier ladder: explicit product override (Piglet Binary baked version, or PIG_INSTALL_TIER for deployments), then package-manager ownership, then writable standalone, then read-only/Windows/ unknown remediation.
type SelfUpdateTier ¶
type SelfUpdateTier string
pig divergence (D39): SelfUpdateTier selects one owner before mutation.
const ( // TierStandalone is a writable standalone binary that pig replaces in // place from the configured update source. TierStandalone SelfUpdateTier = "standalone" // TierPackageManager is an installation owned by a global npm/pnpm/yarn/bun // install. The owning manager's exact command applies the update; pig does // not overwrite its file. TierPackageManager SelfUpdateTier = "package-manager" // TierImmutableBinary is a baked Piglet/Piglet Binary release. Its owning // release is rebuilt and re-pulled; pig does not drift the baked // composition in place. TierImmutableBinary SelfUpdateTier = "immutable-binary" // TierContainer is an OCI image or Piglet Image deployment. The // authenticated pull/redeploy path is reported; pig does not rewrite a // running image. TierContainer SelfUpdateTier = "container" // TierUnsupported covers read-only, Windows in-place-unsupported, and // unknown-provenance installations. Pig refuses mutation and reports the // executable path plus concrete remediation. TierUnsupported SelfUpdateTier = "unsupported" )
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session manages a single JSONL session file. All mutations append entries; no entry is ever rewritten or deleted (the parentId/leafID dance is how branches and undo work: abandoned entries simply become orphaned subtrees in the same file).
func NewSession ¶
NewSession creates a new in-memory session with an ISO millisecond header timestamp (not yet persisted).
func (*Session) Accounting ¶
func (s *Session) Accounting() SessionAccounting
func (*Session) AppendBashExecution ¶
func (s *Session) AppendBashExecution(command, output string, exitCode *int, cancelled, truncated bool, fullOutputPath string, excludeFromContext bool) (string, error)
AppendBashExecution persists a `!cmd` invocation. Returns the new entry id (the new leaf). The caller has already chosen excludeFromContext (true for `!!cmd`).
func (*Session) AppendBranchSummary ¶
func (s *Session) AppendBranchSummary(parentID *string, summary string, details any, fromHook bool, usage *ai.Usage) (string, error)
AppendBranchSummary starts a new branch at parentID with a summary of the abandoned path. parentID is the explicit parent: nil means the entry is a root-level node (no parent). fromId records the leaf being abandoned ("root" when there is none). The new entry becomes the leaf.
Mirrors upstream branchWithSummary(branchFromId: string | null, ...) in session-manager.ts.
func (*Session) AppendCompaction ¶
func (s *Session) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int, details any, fromHook bool, usage *ai.Usage) (string, error)
AppendCompaction records a compaction event as a new leaf. Mirrors upstream SessionManager.appendCompaction (session-manager.ts). An empty firstKeptEntryID is Pi's null: the entry stores its own ID, so the compaction retains no preceding entries. The entry also records the current projected system state, when there is one, stamped with the entry time.
func (*Session) AppendContextEdit ¶
func (s *Session) AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
AppendContextEdit appends a branch-local edit to an earlier model-visible entry and returns the new entry ID (session-manager.ts appendContextEdit). A nil replacement omits the target. The target must be on the active branch and be a user, assistant, or tool-result message entry, or a custom_message entry. String replacements for assistant and tool-result targets are stored as one text block because those roles require content arrays.
func (*Session) AppendCustomMessage ¶
func (s *Session) AppendCustomMessage(customType string, content any, display bool, details any) (string, error)
AppendCustomMessage persists an extension-injected custom message as a "custom_message" entry and returns the new entry id.
func (*Session) AppendEntry ¶
AppendEntry appends an entry to the session (memory + file). The caller must have already filled in `id`, `parentId`, `timestamp` fields on the entry struct: but if `parentId` is nil-ptr AND session has a current leafID, we wire it up automatically so callers can skip the boilerplate.
Returns an error if marshalling, parsing, or file write fails.
func (*Session) AppendLabelChange ¶
AppendLabelChange writes a label entry for targetID. label=nil clears any existing label. Mirrors upstream appendLabelChange in session-manager.ts (line 1006).
func (*Session) AppendMessage ¶
func (s *Session) AppendMessage(msg agent.AgentMessage) (string, error)
AppendMessage persists one upstream AgentMessage, generating a fresh entry id and timestamp and linking it to the current leaf.
func (*Session) AppendModelSwitch ¶
AppendModelSwitch persists a `model_change` audit entry recording that the user switched models mid-session. Mirrors upstream session-manager.ts:appendModelChange(provider, modelId).
func (*Session) AppendThinkingLevelChange ¶
AppendThinkingLevelChange persists a thinking_level_change audit entry. Mirrors upstream agentSession.appendThinkingLevelChange (agent-session.ts). Called when the user cycles the thinking level via Shift+Tab.
func (*Session) AppendUsage ¶
func (s *Session) AppendUsage(kind, provider, model string, usage ai.Usage, note string) (UsageEntry, error)
AppendUsage appends model-attributed usage that does not participate in LLM context and returns the appended entry. Mirrors upstream SessionManager.appendUsage (session-manager.ts).
func (*Session) Branch ¶
func (s *Session) Branch(leafID string) []SessionEntry
Branch returns the path-to-root chain (in append order: root first, leaf last) ending at leafID. Returns nil if leafID isn't an entry.
func (*Session) BuildContext ¶
func (s *Session) BuildContext(leafID *string) []agent.AgentMessage
BuildContext returns the model-visible message list for the path ending at leafID, or at the current leaf when leafID is nil. It is the Messages field of the canonical session projection (session-manager.ts buildSessionContext), so latest compaction, retained entries, and context_edit entries on that path all apply. An unset current leaf (SetLeafID(nil)) yields no messages.
func (*Session) BuildSessionProjection ¶
func (s *Session) BuildSessionProjection() SessionProjection
BuildSessionProjection returns the provenance-preserving projection of the current branch (session-manager.ts SessionManager.buildSessionProjection).
func (*Session) Entries ¶
func (s *Session) Entries() []SessionEntry
Entries returns a copy of all session entries (in append order).
func (*Session) EntryByID ¶
func (s *Session) EntryByID(id string) (SessionEntry, bool)
EntryByID looks up a session entry by its hex ID. Returns false if the ID isn't present. Used by the chat layer to render markers (e.g. branch-summary chip on fork) without exporting the byID map.
func (*Session) FooterUsageTotals ¶
func (s *Session) FooterUsageTotals() footerUsageTotals
FooterUsageTotals returns the footer's all-entry usage totals without building the per-model breakdown.
func (*Session) Fork ¶
Fork moves the leaf pointer to forkFromID so the next AppendEntry becomes a sibling branch off that point. Existing entries are not touched: abandoned tail simply becomes an orphan subtree.
Mirrors upstream `branch(id)`. Use SetLeafID(nil) for the "fork before first entry" case (root-reset).
func (*Session) GetBranch ¶
func (s *Session) GetBranch() []SessionEntry
GetBranch returns the root-to-leaf path of the current leaf. Mirrors upstream SessionManager.getBranch() without an argument.
func (*Session) GetSessionName ¶
GetSessionName returns the latest user-defined session name (set via `/name`), or empty string when none has been set. Mirrors upstream `core/session-manager.ts::getSessionName` (v0.69.0:923-933): walks entries in reverse, returns the trimmed name from the most recent `session_info` entry; an empty trimmed name explicitly clears the name (later session_info entries with empty `name` field shadow earlier non-empty ones).
func (*Session) Header ¶
func (s *Session) Header() SessionHeader
func (*Session) LatestCompactionTimestampMs ¶
LatestCompactionTimestampMs returns the epoch-millisecond timestamp of the most recent compaction entry on the active branch (the path from the current leaf root-ward), and true when such an entry exists. Mirrors upstream getLatestCompactionEntry(getBranch()) (session-manager.ts:311), used by _checkCompaction to skip a stale pre-compaction usage reading that would otherwise re-trigger compaction on the first prompt after a resume.
func (*Session) LeafID ¶
LeafID returns the ID of the current leaf entry (the parent of the next AppendEntry). nil = "no entries yet, next append is a root".
func (*Session) ParentSession ¶
func (*Session) SetLeafID ¶
SetLeafID moves the leaf pointer. Pass nil to reset to "before first entry" (next append becomes a new root). Returns an error if the supplied id isn't an existing entry.
func (*Session) Tree ¶
func (s *Session) Tree() *SessionTreeNode
Tree builds a SessionTreeNode rooted at the (synthetic) root. Children sorted by timestamp (oldest first). When multiple entries have parentId=nil we group them under a synthetic root with empty Entry.
func (*Session) UndecodableCount ¶
UndecodableCount returns how many distinct message entries failed to decode. Such entries are omitted from BuildContext, so a non-zero count means the reconstructed conversation is missing turns. Only entries already visited by messageFor are counted, so callers should read it after a full walk such as BuildContext.
type SessionAccounting ¶
type SessionAccounting struct {
UserMessages int
AssistantMessages int
ToolCalls int
ToolResults int
TotalMessages int
Tokens SessionTokenStats
UsageBreakdown []SessionUsageBreakdown
CacheWaste SessionCacheWaste
// LatestCacheHitRate is the cache-read share (percent) of the last
// assistant message's prompt, nil when that prompt had no tokens.
LatestCacheHitRate *float64
}
SessionAccounting is the immutable all-entry accounting maintained with a Session.
type SessionCacheWaste ¶
SessionCacheWaste reports prompt tokens that a preceding request made cacheable but a later request did not read from cache.
type SessionEntry ¶
type SessionEntry struct {
Base SessionEntryBase
// contains filtered or unexported fields
}
SessionEntry is the union of all entry types. We keep the raw JSON alongside parsed-base fields so unknown fields survive round-trips (forward-compat: future versions of upstream may add fields we don't know about; we must not silently drop them).
func BugReportBranch ¶
func BugReportBranch(session *Session) []SessionEntry
BugReportBranch returns the entries on the current branch.
func NewSessionEntry ¶
func NewSessionEntry(raw json.RawMessage, base SessionEntryBase) SessionEntry
NewSessionEntry constructs a SessionEntry from raw JSON and a pre-decoded base. Used primarily by tests and external packages that need to fabricate entries.
func (SessionEntry) AsMessage ¶
func (e SessionEntry) AsMessage() (MessageEntry, bool)
AsMessage decodes the entry as a MessageEntry. Returns (zero, false) if the entry isn't type=message.
func (SessionEntry) MarshalJSON ¶
func (e SessionEntry) MarshalJSON() ([]byte, error)
func (SessionEntry) Raw ¶
func (e SessionEntry) Raw() json.RawMessage
Raw returns the entry's on-disk JSON as immutable bytes.
type SessionEntryBase ¶
type SessionEntryBase struct {
Type string `json:"type"`
ID string `json:"id"`
ParentID *string `json:"parentId"`
Timestamp string `json:"timestamp"`
}
SessionEntryBase is the common prefix on every non-header entry. `ParentID` is `*string` (not "") so we can distinguish "root entry" (parentId: null) from "missing field". The wire format requires `"parentId": null` literally for roots.
type SessionHeader ¶
type SessionHeader struct {
Type string `json:"type"` // always "session"
Version int `json:"version,omitempty"`
ID string `json:"id"`
Timestamp string `json:"timestamp"`
CWD string `json:"cwd"`
// ParentSession holds the absolute path of the SOURCE jsonl on a
// clone (separate JSONL with linear path-to-leaf snapshot). Empty
// on plain Create.
ParentSession string `json:"parentSession,omitempty"`
}
type SessionInfo ¶
type SessionInfo struct {
Path string
ID string
CWD string
Name string // user-set name (via /name): empty when unset
ParentSession string // path of source jsonl when this session is a clone
Created time.Time
Modified time.Time
MessageCount int
FirstMessage string // first user message text: for picker preview
AllMessagesText string // concatenated text: for fuzzy search
}
SessionInfo is the picker-display summary of a session JSONL. Returned by ListSessions; consumed by /resume picker (TUI overlay follow-up) and by --continue startup flag.
type SessionInfoEntry ¶
type SessionInfoEntry struct {
SessionEntryBase
Name string `json:"name,omitempty"`
}
SessionInfoEntry stores a session-level name (set via `/name`). Persisted as type=session_info so it survives across resumes.
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager owns the on-disk sessions directory for a given cwd and tracks the active session.
func NewSessionManager ¶
func NewSessionManager(cwd string) *SessionManager
NewSessionManager creates a SessionManager for the given working dir.
func NewSessionManagerWithDir ¶
func NewSessionManagerWithDir(cwd, dir string) *SessionManager
NewSessionManagerWithDir overrides the default session directory (tests use this; production callers pass the result of defaultSessionDir).
func (*SessionManager) CWD ¶
func (sm *SessionManager) CWD() string
CWD returns the working directory.
func (*SessionManager) Clone ¶
func (sm *SessionManager) Clone(source *Session, leafID string) (*Session, error)
Clone snapshots the path-to-leafID from `source` and writes it as a brand-new JSONL with a fresh session ID. The new file's header has `parentSession` pointing at the source path. The cloned session becomes the manager's current session.
The cloned file contains a LINEAR chain (no branches): all entries off the chosen leaf path are dropped. This is what makes /clone useful: it produces a self-contained "best path" sub-session.
Mirrors upstream `forkFrom` + `createBranchedSession`.
func (*SessionManager) Create ¶
func (sm *SessionManager) Create(id, parentSessionPath string) (*Session, error)
Create creates a new session file on disk. parentSessionPath is non-empty only when this Create was invoked by Clone: it goes into the new file's header as `parentSession`.
func (*SessionManager) Current ¶
func (sm *SessionManager) Current() *Session
Current returns the active session.
func (*SessionManager) DeleteSession ¶
func (sm *SessionManager) DeleteSession(path string) error
DeleteSession removes a session file from disk. Returns error if the path doesn't exist or can't be removed. Mirrors upstream session-selector.ts delete functionality.
func (*SessionManager) FindByID ¶
func (sm *SessionManager) FindByID(id string) string
FindByID locates a session jsonl whose header `id` matches the given id (anywhere in the manager's session dir). Returns "" when no match. Used by `--session <id>`.
func (*SessionManager) FindMostRecent ¶
func (sm *SessionManager) FindMostRecent() string
FindMostRecent returns the path to the most-recently-modified valid session jsonl in this manager's directory, or "" when none exist.
func (*SessionManager) FindMostRecentForContinue ¶
func (sm *SessionManager) FindMostRecentForContinue() string
FindMostRecentForContinue selects the session to resume for the `--continue` flag, mirroring upstream `SessionManager.continueRecent` (session-manager.ts). When this manager's directory is the cwd-encoded default it holds only this cwd's sessions, so the newest wins outright. When it is a custom `--session-dir` that may be shared across projects, the result is filtered to the newest session whose header cwd refers to this cwd (upstream's `filterCwd` branch) so `--continue` never resumes another project's session.
func (*SessionManager) ForkFromFile ¶
func (sm *SessionManager) ForkFromFile(sourcePath string) (*Session, error)
ForkFromFile copies every non-header entry from sourcePath into a brand-new JSONL with a fresh session ID whose header records `parentSession` = the absolute source path. Unlike Clone (which keeps only the linear path to a chosen leaf), this preserves the full entry tree, matching upstream SessionManager.forkFrom used by `pig --fork`. The new file is written to disk immediately and becomes the manager's current session.
func (*SessionManager) ForkToNewSession ¶
func (sm *SessionManager) ForkToNewSession(source *Session, userMsgEntryID string) (*Session, string, error)
ForkToNewSession creates a NEW session file branched at the PARENT of userMsgEntryID (so the selected user message itself is excluded) and switches sm's current session to it. It returns the new session and the selected message's text, which the caller prefills into the editor for modification. Mirrors upstream AgentSessionRuntime.fork() with the default position "before": createBranchedSession(selectedEntry.parentId), or a fresh session carrying `parentSession` when the selected message is the root.
func (*SessionManager) ListAllSessions ¶
func (sm *SessionManager) ListAllSessions() ([]SessionInfo, error)
ListAllSessions returns every valid session JSONL under <agentDir>/sessions/*/*.jsonl, newest modified first. Mirrors upstream session selector "All" scope.
func (*SessionManager) ListCurrentSessions ¶
func (sm *SessionManager) ListCurrentSessions() ([]SessionInfo, error)
ListCurrentSessions returns the selector's Current Folder scope. A custom session directory may contain sessions from several projects, so it filters by header cwd; the default encoded directory is already cwd-scoped.
func (*SessionManager) ListSessions ¶
func (sm *SessionManager) ListSessions() ([]SessionInfo, error)
ListSessions returns every valid jsonl in this manager's session directory, newest mtime first. Files that fail header parsing are silently skipped (matches upstream: corrupted sessions shouldn't crash the picker).
func (*SessionManager) Load ¶
func (sm *SessionManager) Load(path string) (*Session, error)
Load reads a session JSONL into memory and makes it the current session.
func (*SessionManager) RenameSession ¶
func (sm *SessionManager) RenameSession(path, newName string) error
RenameSession updates the session name by appending a session_info entry. Mirrors upstream session-selector.ts rename functionality.
func (*SessionManager) SessionDir ¶
func (sm *SessionManager) SessionDir() string
SessionDir returns the session directory.
type SessionProjection ¶
type SessionProjection struct {
Entries []ProjectedSessionEntry
Messages []agent.AgentMessage
}
SessionProjection is the provenance-preserving, compaction-aware model context of one branch (session-manager.ts SessionProjection).
func BuildSessionProjection ¶
func BuildSessionProjection(pathEntries []SessionEntry) SessionProjection
BuildSessionProjection projects a root-to-leaf entry path (session-manager.ts buildSessionProjection with the path's final entry as leaf). Compaction preparation uses it on SessionManager.getBranch() output.
type SessionTokenStats ¶
type SessionTokenStats struct {
Input int
Output int
CacheRead int
CacheWrite int
Total int
Cost float64 // USD; only shown if > 0
}
SessionTokenStats holds token usage for the /session display. Mirrors upstream SessionStats.tokens (agent-session.ts:2913-2918).
type SessionTreeNode ¶
type SessionTreeNode struct {
Entry SessionEntry
Children []*SessionTreeNode
Label string
// LabelTimestamp is the on-disk timestamp of the LabelEntry that
// set Label, in upstream's ISO-8601-ish wire format. Empty when
// no label is set. Used by the /tree picker to render `hh:mm`
// next to the label when the user toggles label timestamps on
// (mirrors upstream tree-selector.ts:678-682).
LabelTimestamp string
}
SessionTreeNode is a defensive copy of the session's branch structure for the /tree overlay (follow-up).
type SessionUsageBreakdown ¶
SessionUsageBreakdown attributes billed usage to a model or to host-side summaries.
type Settings ¶
type Settings struct {
DefaultProvider string `json:"defaultProvider,omitempty"`
DefaultModel string `json:"defaultModel,omitempty"`
DefaultThinkingLevel string `json:"defaultThinkingLevel,omitempty"`
// HideThinkingBlock mirrors upstream settings.hideThinkingBlock
// (settings-manager.ts:77). When true, thinking blocks show as
// "Thinking..." stubs instead of the full reasoning trace. Toggled
// by Ctrl+T; persisted so the preference survives sessions.
HideThinkingBlock bool `json:"hideThinkingBlock,omitempty"`
Theme string `json:"theme,omitempty"`
ShellPath string `json:"shellPath,omitempty"`
// CommandPrefix prepended to every bash tool invocation as a
// separate first line (e.g. "set -e\n" or "export PATH=...\n").
CommandPrefix string `json:"commandPrefix,omitempty"`
QuietStartup bool `json:"quietStartup,omitempty"`
Packages []PackageSource `json:"packages,omitempty"`
Extensions []string `json:"extensions,omitempty"`
Skills []string `json:"skills,omitempty"`
Prompts []string `json:"prompts,omitempty"`
Themes []string `json:"themes,omitempty"`
SessionDir string `json:"sessionDir,omitempty"`
HTTPIdleTimeoutMs *int `json:"httpIdleTimeoutMs,omitempty"`
EnabledModels []string `json:"enabledModels,omitempty"`
// DefaultTools is the initial built-in tool selection; nil means the
// upstream default read, bash, edit and write.
DefaultTools []string `json:"defaultTools,omitempty"`
// ModelThinkingLevels holds per-model default thinking levels keyed by
// "provider/modelId".
ModelThinkingLevels map[string]string `json:"modelThinkingLevels,omitempty"`
// CacheWarming is read from global settings only, because each refresh
// costs money. Mirrors upstream settings.cacheWarming.
CacheWarming CacheWarmingMode `json:"cacheWarming,omitempty"`
// LastChangelogVersion records the binary version at which the
// user last saw the startup changelog notification. Used to gate
// "what's new" display to only new entries since last run.
// Mirrors upstream settings.lastChangelogVersion (settings-manager.ts:66).
LastChangelogVersion string `json:"lastChangelogVersion,omitempty"`
// Compaction mirrors upstream settings.compaction (settings-manager.ts:74).
// Nested to match upstream JSON schema:
// { "compaction": { "enabled": true, "reserveTokens": 16384, "keepRecentTokens": 20000 } }
Compaction *CompactionSettingsJSON `json:"compaction,omitempty"`
// BranchSummary mirrors upstream settings.branchSummary
// (settings-manager.ts:75). Nested to match upstream JSON schema:
// { "branchSummary": { "skipPrompt": true, "reserveTokens": 16384 } }
BranchSummary *BranchSummaryConfig `json:"branchSummary,omitempty"`
// DoubleEscapeAction controls what double-Esc with empty editor does.
// Values: "fork", "tree", "none". Default: "tree".
// Mirrors upstream settings.doubleEscapeAction (settings-manager.ts:93).
DoubleEscapeAction string `json:"doubleEscapeAction,omitempty"`
// TreeFilterMode controls the default /tree filter.
// Values: "default", "no-tools", "user-only", "labeled-only", "all".
// Default: "default".
// Mirrors upstream settings.treeFilterMode (settings-manager.ts:94).
TreeFilterMode string `json:"treeFilterMode,omitempty"`
// DefaultProjectTrust is the fallback when no extension or saved decision
// resolves project trust. Values: "ask" | "always" | "never". Default: "ask".
// Global setting only. Mirrors upstream settings.defaultProjectTrust
// (settings-manager.ts:94).
DefaultProjectTrust string `json:"defaultProjectTrust,omitempty"`
// SteeringMode controls queue dispatch when multiple messages are queued.
// Values: "all" | "one-at-a-time". Default: "one-at-a-time".
// Mirrors upstream settings.steeringMode (settings-manager.ts:71).
SteeringMode string `json:"steeringMode,omitempty"`
// FollowUpMode controls how queued follow-up messages are dispatched.
// Values: "all" | "one-at-a-time". Default: "one-at-a-time".
// Mirrors upstream settings.followUpMode (settings-manager.ts:72).
FollowUpMode string `json:"followUpMode,omitempty"`
// TuiMode selects the regular or fullscreen terminal layout. Default: regular.
TuiMode string `json:"tuiMode,omitempty"`
// FullscreenExitOutput controls whether fullscreen exit prints the transcript
// or restores the previous screen. Values: transcript, resume-hint. Default: transcript.
FullscreenExitOutput string `json:"fullscreenExitOutput,omitempty"`
// FullscreenScrollbar controls fullscreen scrollbars. Values: auto, always,
// hidden. Default: auto; it has no effect in regular mode.
FullscreenScrollbar string `json:"fullscreenScrollbar,omitempty"`
// FullscreenCopyOnSelect controls automatic clipboard copy when a fullscreen
// text selection completes. Default: true; it has no effect in regular mode.
FullscreenCopyOnSelect *bool `json:"fullscreenCopyOnSelect,omitempty"`
// CollapseChangelog, when true, shows a condensed "Updated to vX.Y.Z"
// summary instead of the full changelog on /changelog.
// Mirrors upstream settings.collapseChangelog (settings-manager.ts:82).
CollapseChangelog bool `json:"collapseChangelog,omitempty"`
// ShowCacheMissNotices controls transcript notices for significant prompt
// cache misses. Default: false. Mirrors upstream settings.showCacheMissNotices
// (settings-manager.ts:96).
ShowCacheMissNotices bool `json:"showCacheMissNotices,omitempty"`
// EnableSkillCommands, when false, hides skill commands from the
// /skill:name autocomplete popup. Default: true.
// Mirrors upstream settings.enableSkillCommands (settings-manager.ts:89).
// Note: this is a *bool so false can explicitly disable (vs absent=true default).
// Use GetEnableSkillCommands() instead of reading directly.
EnableSkillCommands *bool `json:"enableSkillCommands,omitempty"`
// EnableInstallTelemetry controls whether package-install telemetry may be sent
// by pig-specific install telemetry hooks when they are configured.
// Default: true.
// Mirrors upstream settings.enableInstallTelemetry (settings-manager.ts), but
// the transport itself is a separate implementation concern.
EnableInstallTelemetry *bool `json:"enableInstallTelemetry,omitempty"`
// EnableAnalytics is the opt-in analytics data sharing setting (default
// false). Mirrors upstream settings plumbing only: nothing sends data.
EnableAnalytics *bool `json:"enableAnalytics,omitempty"`
// TrackingID is the analytics tracking identifier generated on the first
// opt-in. Bug reports strip it.
TrackingID string `json:"trackingId,omitempty"`
// Retry mirrors upstream settings.retry (settings-manager.ts:682-690).
// Nested JSON: { "retry": { "enabled": true, "maxRetries": 2,
// "baseDelayMs": 10000, "maxDelayMs": 60000 } }
Retry *RetrySettingsJSON `json:"retry,omitempty"`
// ShowImages controls whether inline images are rendered in tool results
// and assistant messages. Default: true.
// Mirrors upstream settings.showImages (settings-manager.ts:84).
ShowImages *bool `json:"showImages,omitempty"`
// ImageWidthCells is the max width (in terminal columns) for inline images.
// Default: 60. Mirrors upstream settings.imageWidthCells (settings-manager.ts:85).
ImageWidthCells int `json:"imageWidthCells,omitempty"`
// BlockImages, when true, blocks image rendering entirely. Default: false.
// Mirrors upstream settings.blockImages (settings-manager.ts:86).
BlockImages bool `json:"blockImages,omitempty"`
// ImageAutoResize, when true, automatically resizes images to fit the
// terminal width. Default: true.
// Mirrors upstream settings.imageAutoResize (settings-manager.ts:87).
ImageAutoResize *bool `json:"imageAutoResize,omitempty"`
// Transport controls HTTP transport behavior.
// Values: "sse" | "websocket" | "websocket-cached" | "auto". Default: "auto".
// Mirrors upstream settings.transport (settings-manager.ts:70).
Transport string `json:"transport,omitempty"`
// ShowHardwareCursor controls whether the hardware cursor is shown.
// Default: false (or PI_HARDWARE_CURSOR=1 env).
// Mirrors upstream settings.showHardwareCursor (settings-manager.ts:944).
ShowHardwareCursor *bool `json:"showHardwareCursor,omitempty"`
// EditorPaddingX is horizontal padding (in cells) for the editor.
// Range: 0-3. Default: 0.
// Mirrors upstream settings.editorPaddingX (settings-manager.ts:951).
EditorPaddingX *int `json:"editorPaddingX,omitempty"`
// OutputPad is horizontal padding (in cells) for chat output.
// Range: 0-1. Default: 1.
// Mirrors upstream settings.outputPad (settings-manager.ts:116).
OutputPad *int `json:"outputPad,omitempty"`
// ExternalEditor is the command Ctrl+G uses before VISUAL/EDITOR fallbacks.
// Mirrors upstream settings.externalEditor (settings-manager.ts:93).
ExternalEditor string `json:"externalEditor,omitempty"`
// AutocompleteMaxVisible is the max number of autocomplete suggestions shown.
// Range: 3-20. Default: 5.
// Mirrors upstream settings.autocompleteMaxVisible (settings-manager.ts:958).
AutocompleteMaxVisible *int `json:"autocompleteMaxVisible,omitempty"`
// ClearOnShrink controls whether the screen is cleared when terminal shrinks.
// Default: false.
// Mirrors upstream settings.clearOnShrink (settings-manager.ts:891).
ClearOnShrink *bool `json:"clearOnShrink,omitempty"`
// ShowTerminalProgress controls OSC 9;4 terminal progress indicators.
// Default: false.
ShowTerminalProgress *bool `json:"showTerminalProgress,omitempty"`
// ThinkingBudgets controls per-level token budgets for extended thinking.
// Mirrors upstream settings.thinkingBudgets (settings-manager.ts:857).
ThinkingBudgets *ThinkingBudgetsSettings `json:"thinkingBudgets,omitempty"`
// NpmCommand overrides the npm command used for package operations.
// Default: ["npm"].
// Mirrors upstream settings.npmCommand (settings-manager.ts:830).
NpmCommand []string `json:"npmCommand,omitempty"`
// Markdown holds markdown rendering settings.
// Mirrors upstream settings.markdown (settings-manager.ts:965).
Markdown *MarkdownSettings `json:"markdown,omitempty"`
// Warnings holds persisted warning-dismissal preferences.
Warnings *WarningSettings `json:"warnings,omitempty"`
// contains filtered or unexported fields
}
Settings mirrors upstream Settings interface.
func (Settings) GetAutocompleteMaxVisible ¶
GetAutocompleteMaxVisible returns max autocomplete items. Default: 5.
func (Settings) GetBlockImages ¶
GetBlockImages returns whether image rendering is blocked entirely.
func (Settings) GetClearOnShrink ¶
GetClearOnShrink returns whether screen clears on terminal shrink. Default: false.
func (Settings) GetCodeBlockIndent ¶
GetCodeBlockIndent returns the markdown code block indent string. Default: " ".
func (Settings) GetCollapseChangelog ¶
GetCollapseChangelog returns whether changelog output is collapsed.
func (Settings) GetCommandPrefix ¶
func (Settings) GetEditorPaddingX ¶
GetEditorPaddingX returns horizontal editor padding. Default: 0.
func (Settings) GetHideThinkingBlock ¶
GetHideThinkingBlock returns whether thinking blocks should be hidden.
func (Settings) GetImageAutoResize ¶
GetImageAutoResize returns whether images should auto-resize. Default true.
func (Settings) GetImageWidthCells ¶
GetImageWidthCells returns the max image width in columns. Default 60.
func (Settings) GetOutputPad ¶
GetOutputPad returns horizontal output padding. Range: 0-1. Default: 1.
func (Settings) GetQuietStartup ¶
GetQuietStartup returns whether startup output should be reduced.
func (Settings) GetShellPath ¶
GetShellPath satisfies tools.SettingsView so the bash tool can resolve the user's preferred shell without importing internal/codingagent (which would create a cycle).
func (Settings) GetShowCacheMissNotices ¶
GetShowCacheMissNotices returns whether transcript cache-miss notices are shown.
func (Settings) GetShowHardwareCursor ¶
GetShowHardwareCursor returns whether the hardware cursor is shown. Default: false (or PI_HARDWARE_CURSOR=1 env).
func (Settings) GetShowImages ¶
GetShowImages returns whether inline images should be rendered. Default true.
func (Settings) GetShowTerminalProgress ¶
GetShowTerminalProgress returns whether OSC 9;4 terminal progress indicators are enabled.
func (Settings) GetTerminalCapabilityOverrides ¶
func (s Settings) GetTerminalCapabilityOverrides() tui.CapabilityOverrides
GetTerminalCapabilityOverrides mirrors upstream SettingsManager.getTerminalCapabilityOverrides: terminal.images "kitty" or "iterm2" selects that protocol and false disables images; a boolean terminal.trueColor or terminal.hyperlinks overrides detection. "auto" and any other value leave detection alone.
func (Settings) MarshalJSON ¶
MarshalJSON emits upstream's settings wire shape while preserving pig's internal flattened representation.
func (*Settings) UnmarshalJSON ¶
UnmarshalJSON accepts upstream's settings wire shape and legacy pig flat aliases for backward compatibility.
type SettingsError ¶
type SettingsError struct {
Scope string
// Path is the settings file behind the error. Mirrors upstream
// SettingsError.path, which file-backed storage always sets.
Path string
Error error
}
SettingsError mirrors upstream settings-manager.ts load/write diagnostics.
type SettingsManager ¶
type SettingsManager struct {
// contains filtered or unexported fields
}
SettingsManager loads and merges settings from global and project scopes. Merge order: global defaults → project → CLI flags.
func NewSettingsManager ¶
func NewSettingsManager(cwd, agentDir string) *SettingsManager
NewSettingsManager creates a SettingsManager for the given directories.
func NewSettingsManagerWithProjectTrust ¶
func NewSettingsManagerWithProjectTrust(cwd, agentDir string, projectTrusted bool) *SettingsManager
NewSettingsManagerWithProjectTrust creates a settings manager that reads project settings only when projectTrusted is true.
func (*SettingsManager) AgentDir ¶
func (sm *SettingsManager) AgentDir() string
AgentDir returns the global settings directory backing this manager.
func (*SettingsManager) ApplyOverrides ¶
func (sm *SettingsManager) ApplyOverrides(overrides Settings)
ApplyOverrides applies non-persistent overrides on top of the merged settings. Mirrors upstream SettingsManager.applyOverrides.
func (*SettingsManager) CWD ¶
func (sm *SettingsManager) CWD() string
CWD returns the project directory backing this manager.
func (*SettingsManager) DrainErrors ¶
func (sm *SettingsManager) DrainErrors() []SettingsError
DrainErrors returns accumulated load/write diagnostics and clears them.
func (*SettingsManager) Flush ¶
func (sm *SettingsManager) Flush() error
Flush waits for queued writes. pig writes settings synchronously, so this is a no-op. Mirrors upstream SettingsManager.flush() API for parity.
func (*SettingsManager) Get ¶
func (sm *SettingsManager) Get() Settings
Get returns the merged settings.
func (*SettingsManager) GetAutocompleteMaxVisible ¶
func (sm *SettingsManager) GetAutocompleteMaxVisible() int
GetAutocompleteMaxVisible returns max autocomplete items visible.
func (*SettingsManager) GetBlockImages ¶
func (sm *SettingsManager) GetBlockImages() bool
GetBlockImages returns whether image rendering is blocked entirely.
func (*SettingsManager) GetBranchSummarySettings ¶
func (sm *SettingsManager) GetBranchSummarySettings() BranchSummaryConfig
GetBranchSummarySettings returns branch summary settings, applying any reserve-token override from the merged settings. Mirrors upstream SettingsManager.getBranchSummarySettings (settings-manager.ts).
func (*SettingsManager) GetBranchSummarySkipPrompt ¶
func (sm *SettingsManager) GetBranchSummarySkipPrompt() bool
GetBranchSummarySkipPrompt returns whether branch-summary prompt skipping is enabled.
func (*SettingsManager) GetCacheWarmingMode ¶
func (sm *SettingsManager) GetCacheWarmingMode() CacheWarmingMode
GetCacheWarmingMode returns the global cache-warming mode, or "streaming" when it is unset or invalid. Project settings are ignored because each refresh costs money. Mirrors upstream getCacheWarmingMode.
func (*SettingsManager) GetClearOnShrink ¶
func (sm *SettingsManager) GetClearOnShrink() bool
GetClearOnShrink returns whether screen clears on terminal shrink.
func (*SettingsManager) GetCodeBlockIndent ¶
func (sm *SettingsManager) GetCodeBlockIndent() string
GetCodeBlockIndent returns the markdown code block indent string.
func (*SettingsManager) GetCollapseChangelog ¶
func (sm *SettingsManager) GetCollapseChangelog() bool
GetCollapseChangelog returns whether to show a condensed changelog. Default: false. Mirrors upstream getCollapseChangelog (settings-manager.ts:743).
func (*SettingsManager) GetCompactionEnabled ¶
func (sm *SettingsManager) GetCompactionEnabled() bool
GetCompactionEnabled returns whether auto-compaction is enabled.
func (*SettingsManager) GetCompactionKeepRecentTokens ¶
func (sm *SettingsManager) GetCompactionKeepRecentTokens() int
GetCompactionKeepRecentTokens returns the recent-token retention count.
func (*SettingsManager) GetCompactionReserveTokens ¶
func (sm *SettingsManager) GetCompactionReserveTokens() int
GetCompactionReserveTokens returns the compaction reserve token count.
func (*SettingsManager) GetCompactionSettings ¶
func (sm *SettingsManager) GetCompactionSettings() CompactionConfig
GetCompactionSettings returns compaction settings without a model override. Mirrors upstream SettingsManager.getCompactionSettings() called without a model.
func (*SettingsManager) GetDefaultModel ¶
func (sm *SettingsManager) GetDefaultModel() string
GetDefaultModel returns the configured default model, or "".
func (*SettingsManager) GetDefaultProjectTrust ¶
func (sm *SettingsManager) GetDefaultProjectTrust() string
GetDefaultProjectTrust returns the fallback project-trust mode. Values: "ask" | "always" | "never". Default: "ask".
func (*SettingsManager) GetDefaultProvider ¶
func (sm *SettingsManager) GetDefaultProvider() string
GetDefaultProvider returns the configured default provider, or "".
func (*SettingsManager) GetDefaultThinkingLevel ¶
func (sm *SettingsManager) GetDefaultThinkingLevel() string
GetDefaultThinkingLevel returns the configured thinking level, or "".
func (*SettingsManager) GetDefaultTools ¶
func (sm *SettingsManager) GetDefaultTools() []string
GetDefaultTools returns the configured initial built-in tool selection, or nil. Mirrors upstream SettingsManager.getDefaultTools.
func (*SettingsManager) GetDoubleEscapeAction ¶
func (sm *SettingsManager) GetDoubleEscapeAction() string
GetDoubleEscapeAction returns the double-escape action setting. Default: "tree". Mirrors upstream SettingsManager.getDoubleEscapeAction (settings-manager.ts:944-946).
func (*SettingsManager) GetEditorPaddingX ¶
func (sm *SettingsManager) GetEditorPaddingX() int
GetEditorPaddingX returns horizontal editor padding.
func (*SettingsManager) GetEnableAnalytics ¶
func (sm *SettingsManager) GetEnableAnalytics() bool
GetEnableAnalytics reports the opt-in analytics setting (default false). Mirrors upstream SettingsManager.getEnableAnalytics.
func (*SettingsManager) GetEnableInstallTelemetry ¶
func (sm *SettingsManager) GetEnableInstallTelemetry() bool
GetEnableInstallTelemetry returns whether package-install telemetry is enabled. Default: true. This only answers the setting/env gate; it does not imply a transport is configured or that telemetry will actually be delivered.
func (*SettingsManager) GetEnableSkillCommands ¶
func (sm *SettingsManager) GetEnableSkillCommands() bool
func (*SettingsManager) GetEnabledModels ¶
func (sm *SettingsManager) GetEnabledModels() []string
GetEnabledModels returns the list of enabled models for Ctrl+P cycling, or nil.
func (*SettingsManager) GetExtensionPaths ¶
func (sm *SettingsManager) GetExtensionPaths() []string
GetExtensionPaths returns the configured extension paths (from settings).
func (*SettingsManager) GetExternalEditorCommand ¶
func (sm *SettingsManager) GetExternalEditorCommand() string
GetExternalEditorCommand returns the configured external editor command.
func (*SettingsManager) GetFollowUpMode ¶
func (sm *SettingsManager) GetFollowUpMode() string
GetFollowUpMode returns the follow-up queue dispatch mode. Default: "one-at-a-time". Mirrors upstream getFollowUpMode (settings-manager.ts:591).
func (*SettingsManager) GetFullscreenCopyOnSelect ¶
func (sm *SettingsManager) GetFullscreenCopyOnSelect() bool
func (*SettingsManager) GetFullscreenExitOutput ¶
func (sm *SettingsManager) GetFullscreenExitOutput() string
func (*SettingsManager) GetFullscreenScrollbar ¶
func (sm *SettingsManager) GetFullscreenScrollbar() string
func (*SettingsManager) GetGlobalSettings ¶
func (sm *SettingsManager) GetGlobalSettings() Settings
GetGlobalSettings returns the persisted global settings layer.
func (*SettingsManager) GetHideThinkingBlock ¶
func (sm *SettingsManager) GetHideThinkingBlock() bool
GetHideThinkingBlock returns whether thinking blocks should be hidden.
func (*SettingsManager) GetHttpIdleTimeoutMs ¶
func (sm *SettingsManager) GetHttpIdleTimeoutMs() (int, error)
GetHttpIdleTimeoutMs returns the HTTP header/body idle timeout in milliseconds. Default: 300000 (5 minutes). Zero disables the timeout. An unparseable value is an error, as upstream parseTimeoutSetting throws.
func (*SettingsManager) GetImageAutoResize ¶
func (sm *SettingsManager) GetImageAutoResize() bool
GetImageAutoResize returns whether images auto-resize.
func (*SettingsManager) GetImageWidthCells ¶
func (sm *SettingsManager) GetImageWidthCells() int
GetImageWidthCells returns the max image width in columns.
func (*SettingsManager) GetLastChangelogVersion ¶
func (sm *SettingsManager) GetLastChangelogVersion() string
GetLastChangelogVersion returns the last seen changelog version string. Mirrors upstream getLastChangelogVersion (settings-manager.ts:529).
func (*SettingsManager) GetMermaidRenderingMode ¶
func (sm *SettingsManager) GetMermaidRenderingMode() string
func (*SettingsManager) GetModelCompactionSettings ¶
func (sm *SettingsManager) GetModelCompactionSettings(provider, modelID string) CompactionConfig
GetModelCompactionSettings returns compaction settings for one model. Each token setting resolves through compaction.modelOverrides["provider/modelID"], then the ordinary setting, then the built-in default. Empty provider and modelID select no override. Mirrors upstream SettingsManager.getCompactionSettings(model).
func (*SettingsManager) GetModelThinkingLevel ¶
func (sm *SettingsManager) GetModelThinkingLevel(provider, modelID string) string
GetModelThinkingLevel returns the per-model default thinking level for provider/modelID, or "". Mirrors upstream getModelThinkingLevel.
func (*SettingsManager) GetNpmCommand ¶
func (sm *SettingsManager) GetNpmCommand() []string
GetNpmCommand returns the npm command override. Default: nil (use "npm").
func (*SettingsManager) GetOutputPad ¶
func (sm *SettingsManager) GetOutputPad() int
GetOutputPad returns horizontal chat output padding.
func (*SettingsManager) GetPackages ¶
func (sm *SettingsManager) GetPackages() []PackageSource
GetPackages returns the configured package sources.
func (*SettingsManager) GetProjectSettings ¶
func (sm *SettingsManager) GetProjectSettings() Settings
GetProjectSettings returns the persisted project settings layer.
func (*SettingsManager) GetPromptTemplatePaths ¶
func (sm *SettingsManager) GetPromptTemplatePaths() []string
GetPromptTemplatePaths returns the configured prompt template paths (from settings).
func (*SettingsManager) GetProviderRequestTimeoutMs ¶
func (sm *SettingsManager) GetProviderRequestTimeoutMs() (int, error)
GetProviderRequestTimeoutMs returns the effective per-request stream/read timeout: retry.provider.timeoutMs when set, otherwise the httpIdleTimeoutMs. Mirrors upstream sdk.ts:311 (timeoutMs = providerRetrySettings.timeoutMs ?? effectiveTimeoutMs, where effectiveTimeoutMs is the httpIdleTimeoutMs). The sibling maxRetries/maxRetryDelayMs are consumed separately by the provider retry transport (ai.ConfigureProviderRetry).
func (*SettingsManager) GetProviderRetrySettings ¶
func (sm *SettingsManager) GetProviderRetrySettings() ProviderRetryConfig
GetProviderRetrySettings returns provider retry settings with defaults applied. timeoutMs maps onto pig's net/http idle deadline (GetProviderRequestTimeoutMs); maxRetries/maxRetryDelayMs drive the provider retry transport (ai.ConfigureProviderRetry), mirroring the values upstream sdk.ts passes into retryProviderRequest.
func (*SettingsManager) GetQuietStartup ¶
func (sm *SettingsManager) GetQuietStartup() bool
GetQuietStartup returns whether startup messages should be suppressed.
func (*SettingsManager) GetRetryEnabled ¶
func (sm *SettingsManager) GetRetryEnabled() bool
GetRetryEnabled returns whether automatic retries are enabled.
func (*SettingsManager) GetRetrySettings ¶
func (sm *SettingsManager) GetRetrySettings() RetryConfig
GetRetrySettings returns retry settings with defaults applied. Mirrors upstream SettingsManager.getRetrySettings (settings-manager.ts:683-690).
func (*SettingsManager) GetSessionDir ¶
func (sm *SettingsManager) GetSessionDir() (string, error)
GetSessionDir returns the configured session directory, expanding ~ forms and converting a file:// URL. An invalid file URL is an error, as upstream getSessionDir throws Node's fileURLToPath error.
func (*SettingsManager) GetShellCommandPrefix ¶
func (sm *SettingsManager) GetShellCommandPrefix() string
GetShellCommandPrefix returns the command prefix (e.g. "set -e; ").
func (*SettingsManager) GetShellPath ¶
func (sm *SettingsManager) GetShellPath() (string, error)
GetShellPath returns the configured shell path (for bash tool). An invalid file URL is an error, as upstream getShellPath throws.
func (*SettingsManager) GetShowCacheMissNotices ¶
func (sm *SettingsManager) GetShowCacheMissNotices() bool
GetShowCacheMissNotices returns whether transcript cache-miss notices are shown.
func (*SettingsManager) GetShowHardwareCursor ¶
func (sm *SettingsManager) GetShowHardwareCursor() bool
GetShowHardwareCursor returns whether the hardware cursor is shown.
func (*SettingsManager) GetShowImages ¶
func (sm *SettingsManager) GetShowImages() bool
GetShowImages returns whether inline images should be rendered.
func (*SettingsManager) GetShowTerminalProgress ¶
func (sm *SettingsManager) GetShowTerminalProgress() bool
GetShowTerminalProgress returns whether OSC 9;4 terminal progress indicators are enabled.
func (*SettingsManager) GetSkillPaths ¶
func (sm *SettingsManager) GetSkillPaths() []string
GetSkillPaths returns the configured skill paths (from settings).
func (*SettingsManager) GetSteeringMode ¶
func (sm *SettingsManager) GetSteeringMode() string
GetSteeringMode returns the steering queue dispatch mode. Default: "one-at-a-time". Mirrors upstream getSteeringMode (settings-manager.ts:581).
func (*SettingsManager) GetTerminalCapabilityOverrides ¶
func (sm *SettingsManager) GetTerminalCapabilityOverrides() tui.CapabilityOverrides
GetTerminalCapabilityOverrides mirrors upstream SettingsManager.getTerminalCapabilityOverrides over the merged settings.
func (*SettingsManager) GetTheme ¶
func (sm *SettingsManager) GetTheme() string
GetTheme returns the configured theme name, or "".
func (*SettingsManager) GetThemePaths ¶
func (sm *SettingsManager) GetThemePaths() []string
GetThemePaths returns the configured theme paths (from settings).
func (*SettingsManager) GetThinkingBudgets ¶
func (sm *SettingsManager) GetThinkingBudgets() *ThinkingBudgetsSettings
GetThinkingBudgets returns custom thinking budgets, or nil.
func (*SettingsManager) GetTrackingID ¶
func (sm *SettingsManager) GetTrackingID() string
GetTrackingID returns the analytics tracking identifier, or "". Mirrors upstream getTrackingId.
func (*SettingsManager) GetTransport ¶
func (sm *SettingsManager) GetTransport() string
GetTransport returns the configured transport. Default: "auto".
func (*SettingsManager) GetTreeFilterMode ¶
func (sm *SettingsManager) GetTreeFilterMode() string
GetTreeFilterMode returns the default /tree filter mode. Default: "default". Mirrors upstream SettingsManager.getTreeFilterMode (settings-manager.ts:954-955).
func (*SettingsManager) GetTuiMode ¶
func (sm *SettingsManager) GetTuiMode() string
GetEnableSkillCommands returns whether skill commands are shown in autocomplete. Default: true. Mirrors upstream getEnableSkillCommands (settings-manager.ts:847-849).
func (*SettingsManager) GetWarnings ¶
func (sm *SettingsManager) GetWarnings() WarningSettings
GetWarnings returns warning settings.
func (*SettingsManager) GlobalPath ¶
func (sm *SettingsManager) GlobalPath() string
GlobalPath returns the global settings file path.
func (*SettingsManager) GlobalSettingsPath ¶
func (sm *SettingsManager) GlobalSettingsPath() string
GlobalSettingsPath returns the path to the global settings file.
func (*SettingsManager) IsInstallTelemetryEnabled ¶
func (sm *SettingsManager) IsInstallTelemetryEnabled() bool
IsInstallTelemetryEnabled reports whether install/attribution telemetry is enabled, honoring the PI_TELEMETRY env override first and otherwise the enableInstallTelemetry setting (default true). Mirrors upstream isInstallTelemetryEnabled (telemetry.ts:8): when PI_TELEMETRY is set its truthiness wins; otherwise the setting decides. Gates provider attribution headers (provider-attribution.ts) in addition to package-install telemetry. pig divergence (D26): gates the OpenRouter/NVIDIA/Cloudflare attribution headers in coding/model.go.
func (*SettingsManager) IsProjectTrusted ¶
func (sm *SettingsManager) IsProjectTrusted() bool
IsProjectTrusted reports whether project settings are readable and writable.
func (*SettingsManager) Load ¶
func (sm *SettingsManager) Load()
Load reads settings from disk. Errors recorded earlier stay until DrainErrors, as upstream reload keeps them.
func (*SettingsManager) Reload ¶
func (sm *SettingsManager) Reload()
Reload re-reads settings from disk. Call after the user edits settings externally, or after UpdateGlobal to refresh the in-memory view. Mirrors upstream SettingsManager reload semantics.
func (*SettingsManager) RemoveModelThinkingLevel ¶
func (sm *SettingsManager) RemoveModelThinkingLevel(provider, modelID string) error
RemoveModelThinkingLevel clears a per-model default thinking level override. Mirrors upstream removeModelThinkingLevel.
func (*SettingsManager) SetAutocompleteMaxVisible ¶
func (sm *SettingsManager) SetAutocompleteMaxVisible(n int) error
SetAutocompleteMaxVisible sets max autocomplete items. Clamped to 3-20.
func (*SettingsManager) SetBlockImages ¶
func (sm *SettingsManager) SetBlockImages(blocked bool) error
SetBlockImages sets whether image rendering is blocked.
func (*SettingsManager) SetCacheWarmingMode ¶
func (sm *SettingsManager) SetCacheWarmingMode(mode CacheWarmingMode) error
SetCacheWarmingMode persists the cache-warming mode to global settings. Mirrors upstream setCacheWarmingMode.
func (*SettingsManager) SetClearOnShrink ¶
func (sm *SettingsManager) SetClearOnShrink(enabled bool) error
SetClearOnShrink sets whether screen clears on terminal shrink.
func (*SettingsManager) SetCollapseChangelog ¶
func (sm *SettingsManager) SetCollapseChangelog(collapse bool) error
SetCollapseChangelog sets whether changelog is collapsed.
func (*SettingsManager) SetCompactionEnabled ¶
func (sm *SettingsManager) SetCompactionEnabled(enabled bool) error
SetCompactionEnabled enables or disables auto-compaction.
func (*SettingsManager) SetDefaultModel ¶
func (sm *SettingsManager) SetDefaultModel(m string) error
SetDefaultModel sets the default model.
func (*SettingsManager) SetDefaultModelAndProvider ¶
func (sm *SettingsManager) SetDefaultModelAndProvider(provider, model string) error
SetDefaultModelAndProvider sets both default model and provider atomically.
func (*SettingsManager) SetDefaultProvider ¶
func (sm *SettingsManager) SetDefaultProvider(p string) error
SetDefaultProvider sets the default provider.
func (*SettingsManager) SetDefaultThinkingLevel ¶
func (sm *SettingsManager) SetDefaultThinkingLevel(level string) error
SetDefaultThinkingLevel sets the default thinking level.
func (*SettingsManager) SetDoubleEscapeAction ¶
func (sm *SettingsManager) SetDoubleEscapeAction(action string) error
SetDoubleEscapeAction sets the double-escape action.
func (*SettingsManager) SetEditorPaddingX ¶
func (sm *SettingsManager) SetEditorPaddingX(padding int) error
SetEditorPaddingX sets horizontal editor padding. Clamped to 0-3.
func (*SettingsManager) SetEnableAnalytics ¶
func (sm *SettingsManager) SetEnableAnalytics(enabled bool) error
SetEnableAnalytics saves the analytics opt-in. The first opt-in generates a random UUID tracking identifier, which later toggles keep. Mirrors upstream setEnableAnalytics.
func (*SettingsManager) SetEnableInstallTelemetry ¶
func (sm *SettingsManager) SetEnableInstallTelemetry(enabled bool) error
SetEnableInstallTelemetry sets whether package-install telemetry is enabled. This toggles the gate only; delivery depends on the configured sender.
func (*SettingsManager) SetEnableSkillCommands ¶
func (sm *SettingsManager) SetEnableSkillCommands(enabled bool) error
SetEnableSkillCommands sets whether skill commands are enabled.
func (*SettingsManager) SetEnabledModels ¶
func (sm *SettingsManager) SetEnabledModels(patterns []string) error
SetEnabledModels sets the list of enabled models for Ctrl+P cycling.
func (*SettingsManager) SetExtensionPaths ¶
func (sm *SettingsManager) SetExtensionPaths(paths []string) error
func (*SettingsManager) SetFollowUpMode ¶
func (sm *SettingsManager) SetFollowUpMode(mode string) error
SetFollowUpMode sets the follow-up queue dispatch mode.
func (*SettingsManager) SetFullscreenCopyOnSelect ¶
func (sm *SettingsManager) SetFullscreenCopyOnSelect(enabled bool) error
func (*SettingsManager) SetFullscreenExitOutput ¶
func (sm *SettingsManager) SetFullscreenExitOutput(output string) error
func (*SettingsManager) SetFullscreenScrollbar ¶
func (sm *SettingsManager) SetFullscreenScrollbar(mode string) error
func (*SettingsManager) SetHideThinkingBlock ¶
func (sm *SettingsManager) SetHideThinkingBlock(hide bool) error
SetHideThinkingBlock sets whether to hide thinking blocks.
func (*SettingsManager) SetHttpIdleTimeoutMs ¶
func (sm *SettingsManager) SetHttpIdleTimeoutMs(timeoutMs float64) error
SetHttpIdleTimeoutMs sets the HTTP header/body idle timeout in milliseconds. Zero disables the timeout.
func (*SettingsManager) SetImageAutoResize ¶
func (sm *SettingsManager) SetImageAutoResize(enabled bool) error
SetImageAutoResize sets whether images auto-resize.
func (*SettingsManager) SetImageWidthCells ¶
func (sm *SettingsManager) SetImageWidthCells(width int) error
SetImageWidthCells sets the max image width in columns.
func (*SettingsManager) SetLastChangelogVersion ¶
func (sm *SettingsManager) SetLastChangelogVersion(version string) error
SetLastChangelogVersion records that the user has seen changelog entries up to and including version. Persists to global settings. Mirrors upstream setLastChangelogVersion (settings-manager.ts:533-535).
func (*SettingsManager) SetMermaidRenderingMode ¶
func (sm *SettingsManager) SetMermaidRenderingMode(mode string) error
func (*SettingsManager) SetModelThinkingLevel ¶
func (sm *SettingsManager) SetModelThinkingLevel(provider, modelID, level string) error
SetModelThinkingLevel sets a per-model default thinking level override, keyed by "provider/modelID". Mirrors upstream setModelThinkingLevel.
func (*SettingsManager) SetNpmCommand ¶
func (sm *SettingsManager) SetNpmCommand(cmd []string) error
SetNpmCommand sets the npm command override.
func (*SettingsManager) SetOutputPad ¶
func (sm *SettingsManager) SetOutputPad(padding int) error
SetOutputPad sets horizontal chat output padding. Clamped to 0-1.
func (*SettingsManager) SetPackages ¶
func (sm *SettingsManager) SetPackages(pkgs []PackageSource) error
SetPackages persists the global package source list.
func (*SettingsManager) SetProjectExtensionPaths ¶
func (sm *SettingsManager) SetProjectExtensionPaths(paths []string) error
func (*SettingsManager) SetProjectPackages ¶
func (sm *SettingsManager) SetProjectPackages(pkgs []PackageSource) error
SetProjectPackages persists the project package source list.
func (*SettingsManager) SetProjectPromptTemplatePaths ¶
func (sm *SettingsManager) SetProjectPromptTemplatePaths(paths []string) error
func (*SettingsManager) SetProjectSkillPaths ¶
func (sm *SettingsManager) SetProjectSkillPaths(paths []string) error
func (*SettingsManager) SetProjectThemePaths ¶
func (sm *SettingsManager) SetProjectThemePaths(paths []string) error
func (*SettingsManager) SetProjectTrusted ¶
func (sm *SettingsManager) SetProjectTrusted(trusted bool)
SetProjectTrusted changes project-settings access and reloads both layers.
func (*SettingsManager) SetPromptTemplatePaths ¶
func (sm *SettingsManager) SetPromptTemplatePaths(paths []string) error
func (*SettingsManager) SetQuietStartup ¶
func (sm *SettingsManager) SetQuietStartup(quiet bool) error
SetQuietStartup sets whether startup messages are suppressed.
func (*SettingsManager) SetRetryEnabled ¶
func (sm *SettingsManager) SetRetryEnabled(enabled bool) error
SetRetryEnabled enables or disables auto-retry.
func (*SettingsManager) SetShellCommandPrefix ¶
func (sm *SettingsManager) SetShellCommandPrefix(prefix string) error
SetShellCommandPrefix sets the command prefix for bash commands.
func (*SettingsManager) SetShellPath ¶
func (sm *SettingsManager) SetShellPath(path string) error
SetShellPath sets the shell path for the bash tool.
func (*SettingsManager) SetShowCacheMissNotices ¶
func (sm *SettingsManager) SetShowCacheMissNotices(show bool) error
SetShowCacheMissNotices sets whether transcript cache-miss notices are shown.
func (*SettingsManager) SetShowHardwareCursor ¶
func (sm *SettingsManager) SetShowHardwareCursor(enabled bool) error
SetShowHardwareCursor sets whether the hardware cursor is shown.
func (*SettingsManager) SetShowImages ¶
func (sm *SettingsManager) SetShowImages(show bool) error
SetShowImages sets whether inline images are shown.
func (*SettingsManager) SetShowTerminalProgress ¶
func (sm *SettingsManager) SetShowTerminalProgress(enabled bool) error
SetShowTerminalProgress sets whether OSC 9;4 terminal progress indicators are enabled.
func (*SettingsManager) SetSkillPaths ¶
func (sm *SettingsManager) SetSkillPaths(paths []string) error
func (*SettingsManager) SetSteeringMode ¶
func (sm *SettingsManager) SetSteeringMode(mode string) error
SetSteeringMode sets the steering queue dispatch mode.
func (*SettingsManager) SetTheme ¶
func (sm *SettingsManager) SetTheme(theme string) error
func (*SettingsManager) SetThemePaths ¶
func (sm *SettingsManager) SetThemePaths(paths []string) error
func (*SettingsManager) SetTransport ¶
func (sm *SettingsManager) SetTransport(transport string) error
SetTransport sets the HTTP transport mode.
func (*SettingsManager) SetTreeFilterMode ¶
func (sm *SettingsManager) SetTreeFilterMode(mode string) error
SetTreeFilterMode sets the tree filter mode.
func (*SettingsManager) SetTuiMode ¶
func (sm *SettingsManager) SetTuiMode(mode string) error
SetTheme sets the default theme.
func (*SettingsManager) SetWarnings ¶
func (sm *SettingsManager) SetWarnings(warnings WarningSettings) error
SetWarnings sets warning settings.
func (*SettingsManager) UpdateGlobal ¶
func (sm *SettingsManager) UpdateGlobal(fn func(*Settings)) error
UpdateGlobal applies fn to the global settings, persists the result to <agentDir>/settings.json, and reloads the merged view. Mirrors upstream SettingsManager.updateSettings (settings-manager.ts).
func (*SettingsManager) UpdateProject ¶
func (sm *SettingsManager) UpdateProject(fn func(*Settings)) error
UpdateProject applies fn to the project settings, persists the result to <cwd>/.pig/settings.json, and reloads the merged view.
type ShareState ¶
type ShareState struct {
}
ShareState is the agent state the pi.share entry records: upstream session.state.systemPrompt and session.state.tools.
func NewShareState ¶
func NewShareState(systemPrompt string, tools []agent.AgentTool) ShareState
NewShareState captures the system prompt and the active agent tools.
type ShareTool ¶
type ShareTool struct {
}
ShareTool is one tool schema recorded in the pi.share entry.
type SkillDef ¶
type SkillDef struct {
Name string
Description string
DisableModelInvocation bool
// Body is the markdown content (stripped of frontmatter).
Body string
// Path is the source SKILL.md file.
Path string
// Dir is the skill's containing directory: used so callers can
// resolve referenced sibling files.
Dir string
}
SkillDef is a parsed skill: a directory under `<config>/skills/<name>/` containing a `SKILL.md` file with frontmatter (name, description) and markdown body.
Pig loads these on `--skill <name>` and appends the body to the system prompt under a `## Skills` heading.
func DeduplicateSkills ¶
DeduplicateSkills keeps the first definition for each public name, matching Pi's collision behavior after Resource paths are ordered by precedence.
func LoadSkill ¶
LoadSkill loads a skill by name from `<skillsDir>/<name>/SKILL.md`.
Lookup order (mirrors upstream resource-loader's user-vs-project precedence):
- <pig-config>/skills/<name>/SKILL.md
- <skillsDir>/<name>/SKILL.md (caller-provided fallback root)
Most callers pass DefaultAgentDir()/skills as skillsDir so the Pig agent tree is searched first; we keep the parameter so SDK consumers can point at a vendored skills tree without env juggling.
func LoadSkillPath ¶
LoadSkillPath loads a skill from a SKILL.md file path or a skill directory.
func LoadSkills ¶
LoadSkills loads each named skill, returning the first error encountered. On error the returned slice contains skills loaded so far.
func LoadSkillsFromPath ¶
LoadSkillsFromPath loads one or more skills from a path. Supported forms:
- /path/to/skill/SKILL.md
- /path/to/skill-dir/ (contains SKILL.md)
- /path/to/skills-root/ (contains child dirs with SKILL.md)
type SlashCommand ¶
type SlashCommand struct {
Name string
Description string
Handler func(ctx *ExtensionContext, args string) error
}
SlashCommand is a command registered via /name.
type SlashCommandInfo ¶
type SlashCommandInfo struct {
Name string
Aliases []string
Description string
Source SlashCommandSource
}
SlashCommandInfo is the user-facing summary used by `/help`.
type SlashCommandSource ¶
type SlashCommandSource string
SlashCommandSource mirrors upstream's `SlashCommandSource` discriminator.
const ( SlashSourceBuiltin SlashCommandSource = "builtin" SlashSourceExtension SlashCommandSource = "extension" SlashSourcePrompt SlashCommandSource = "prompt" // <agentDir>/prompts/*.md )
type SlashContext ¶
type SlashContext struct {
// Raw args after the command name (already trimmed). Empty if user
// just typed `/foo` with no args.
Args string
// Output sinks: must be non-nil when Dispatch is called.
Append func(string) // append markdown to chat (Markdown component, 1px padding)
AppendText func(string) // append plain ANSI text to chat (Text component, 1px padding)
Clear func() // clear the chat transcript
Quit func() // request session exit
Reset func() // /new: keep transcript visible but reset agent messages
// NewSession creates a fresh session file and resets agent state.
// Mirrors upstream runtimeHost.newSession(). May be nil in test contexts.
NewSession func() error
// FatalRuntimeError records an unrecoverable create/resume/import
// replacement failure, then requests a status-1 exit after TUI teardown.
FatalRuntimeError func(prefix string, err error) error
// ShowStatus appends or updates the status line.
ShowStatus func(msg string)
ShowWarning func(msg string)
// Accessors. Any of these may be nil; handlers must guard. Keeps
// the registry decoupled from the full InteractiveMode struct so
// /help and friends are unit-testable in isolation.
ModelName func() string
ToolNames func() []string
RegisteredTools func() []extension.RegisteredTool
// pi.share entry attached to exported transcripts.
ShareState func() ShareState
// ShareSession uploads an explicitly requested share artifact. The host
// captures the command context so cancellation reaches the HTTP request.
SkillNames func() []string
SessionInfo func() (id, dir string, msgCount int)
LastAssistant func() string
CopyClipboard func(text string) error
CostSummary func() string
HotkeyLines func() []string
// All registered commands: set by Dispatch before calling Handler
// so /help can enumerate the live set.
AllCommands []SlashCommandInfo
// Session accessors. May be nil; handlers must guard.
CurrentSession func() *Session
// CacheWarmingStatus reports the Session's cache warmer, or nil when the
// Session has none.
CacheWarmingStatus func() *CacheWarmingStatus
SetSessionName func(name string) error
GetSessionName func() string
// OnNameChange is called after a successful /name set so callers can
// update the terminal title and status-line footer.
OnNameChange func(name string)
// ForkAtEntry moves the leaf to entryID IN THE SAME FILE (upstream
// `session.branch`). Used by /tree navigation, not /fork.
ForkAtEntry func(entryID string) error
// FlushCompactionQueue delivers messages that were queued while a
// compaction was running. Tree navigation calls it once the new leaf is in
// place, mirroring upstream's flushCompactionQueue after "Navigated to
// selected point" (interactive-mode.ts:1847, 5021), so a message typed
// during compaction is not left queued by navigating away.
FlushCompactionQueue func()
// ForkToNewSession forks the selected user message into a NEW session
// file (branch copied up to the message's parent), switches to it, and
// prefills the editor with the message text. Mirrors upstream /fork
// (agent-session-runtime.ts fork(), position "before").
ForkToNewSession func(userMsgEntryID string) error
// WriteDebugLog writes the current frame and message history to a debug
// log file and returns its path. Backs /debug and the ctrl+shift+d hotkey.
WriteDebugLog func() (path string, err error)
CloneCurrent func() (newPath string, err error)
ListSessions func() ([]SessionInfo, error)
RenderTree func() string
// File-based prompt templates loaded from
// <agentDir>/prompts and <cwd>/.pig/prompts. Read-only snapshot;
// host populates this each Dispatch.
PromptTemplates []PromptTemplate
// Modal selector callbacks. Nil in headless or test
// contexts; handlers must guard and fall back to text mode.
PickSession func() (path string, ok bool)
PickUserMessage func() (entryID string, ok bool)
PickTreeEntry func(initialSelectedID string) (entryID string, ok bool)
// AppendLabelChange writes a label entry for targetID.
// label=="" clears any existing label (upstream: undefined→delete).
AppendLabelChange func(targetID, label string) error
LoadSessionPath func(path string) error
// Manual context compaction.
// CompactSession triggers a manual compact on the current session.
// The closure captures the appropriate context internally.
// nil in headless / test contexts unless explicitly wired.
CompactSession func(customInstructions string) error
// /tree summarize-branch flow.
// ShowExtensionSelector presents a modal string picker with an optional
// description under the title; returns the chosen option and true, or
// ("", false) on cancel (Esc). Mirrors upstream showExtensionSelector()
// and ExtensionSelectorOptions.description.
ShowExtensionSelector func(title string, options []string, description string) (string, bool)
// ShowExtensionEditor presents a text prompt with an optional description
// and prefill; returns the text and true, or ("", false) on cancel (Esc).
// Mirrors upstream showExtensionEditor() and
// ExtensionEditorOptions.description.
ShowExtensionEditor func(title, description, prefill string) (string, bool)
// BugReportInputs snapshots the process state /bug describes (model,
// provider, thinking level, extensions, settings). Nil outside the
// interactive UI.
BugReportInputs func() (BugReportInputs, error)
// BugReportProviderName names the current model's provider for the
// summary consent text. May be nil.
BugReportProviderName func() string
// SummarizeForBugReport writes the /bug summary with the session model
// behind a cancellable loader. aborted reports that the user cancelled.
// May be nil.
SummarizeForBugReport func(modelName, hint string) (summary string, aborted bool, err error)
// UpstreamVersion returns the pinned Pi version. May be nil.
UpstreamVersion func() string
// ShowSettingsList presents the dedicated two-column settings selector.
// Blocks until the user cycles a value (returns id, newValue, true) or
// cancels (returns "", "", false). Mirrors upstream SettingsSelectorComponent.
ShowSettingsList func(items []tui.SettingItem) (changedID, changedValue string, ok bool)
// ShowSelectList presents a non-search submenu selector with optional
// description column. Used by /settings for upstream-style submenus like
// thinking level. Returns the chosen value or ("", false) on cancel.
ShowSelectList func(title, description string, items []tui.SelectItem, currentValue string) (value string, ok bool)
// ShowThemeSelector presents the theme submenu with live preview.
// Used by /settings theme to mirror upstream theme preview semantics.
ShowThemeSelector func(currentTheme string) (themeName string, ok bool)
// AvailableThinkingLevels returns the currently supported levels for the
// active model. Used by /settings to build the thinking submenu.
AvailableThinkingLevels func() []string
// CurrentThinkingLevel and SelectThinkingLevel back /thinking. May be nil.
CurrentThinkingLevel func() string
SelectThinkingLevel func(level string)
// ShowThinkingSelector opens the /thinking selector (upstream
// showThinkingSelector). May be nil; /thinking then falls back to
// ShowSelectList.
ShowThinkingSelector func()
ModelThinkingSubmenu func(string, func(*string)) tui.Component
// summary. Mirrors upstream AgentSession.navigateTree() with summarize flag.
NavigateTreeFull func(ctx context.Context, targetID string, summarize bool, customInstructions string) (NavigateTreeResult, error)
// AbortBranchSummary cancels an in-progress branch summarization.
AbortBranchSummary func()
// SetEditorText sets the editor content (e.g. pre-filling user message
// text when navigating to a user-message entry).
SetEditorText func(text string)
// Mid-session model switch.
SwitchModel func(spec string) error
PickModel func(initialQuery string) (spec string, ok bool)
ResolveModel func(input string) (spec string, ok bool)
// /scoped-models selector.
ShowScopedModels func() // opens editor-slot scoped-models list
// Settings UI.
// SettingsManager provides read/write access to global settings.
SettingsManager *SettingsManager
// Reload triggers a reload of settings and prompt templates.
// Called by the /reload command. May be nil in headless contexts.
Reload func()
// ReloadDiagnostics returns resource counts after a reload.
// Mirrors upstream showLoadedResources with showDiagnosticsWhenQuiet.
// May be nil; handler falls back to a static message.
ReloadDiagnostics func() ReloadDiag
// OnSettingApplied is called after /settings persists a change.
// id is the setting identifier (e.g. "hide-thinking"), value is the new value.
// Interactive mode uses this to apply live state changes (e.g. update
// m.hideThinking without requiring a restart). May be nil.
// Mirrors upstream settings-selector.ts callbacks (onHideThinkingChange etc.).
OnSettingApplied func(id, value string)
// AgentDir is the pig config dir (typically ~/.pig/agent).
// Used by /login and /logout for auth.json access.
AgentDir string
// Parity harness hooks used only by env-gated test slash commands.
ProbeClipboardRead func() (string, error)
ProbeImageFallback func() (string, error)
ProbeCancellableLoader func() (string, error)
ProbeSelectList func() (string, error)
ProbeOAuthCallbackPage func() (string, error)
ProbeCopilotHeaders func() (string, error)
ProbeOAuthCopilot func() (string, error)
ProbeOAuthCopilotEnv func() (string, error)
ProbeOAuthAnthropic func() (string, error)
ProbeOAuthCodex func() (string, error)
// Login runs the interactive OAuth login flow for the given provider.
// ShowOAuthSelector opens the OAuth provider picker overlay.
// mode is "login" or "logout". Returns provider ID and true, or
// "", false if cancelled. nil in headless/test contexts.
ShowOAuthSelector func(mode string) (providerID string, ok bool)
ShowLoginAuthType func() (authType string, ok bool)
// Mirrors upstream showLoginDialog (interactive-mode.ts:4325-4444).
// May be nil in headless/test contexts; handlers must guard.
Login func(ctx context.Context, provider string) error
SetAPIKey func(provider, value string) error
ShowTextInput func(title, placeholder string) (string, bool)
// LoginAPIKeyProvider runs a provider's own api-key login flow and
// reports whether the provider has one (llama.cpp prompts for its server
// URL and optional key instead of a bare key).
LoginAPIKeyProvider func(provider string) bool
// RunLlama runs the built-in /llama command.
RunLlama func() error
// Logout removes stored credentials for the given provider.
// Mirrors upstream showOAuthSelector logout branch (interactive-mode.ts:4299).
// May be nil in headless/test contexts; handlers must guard.
Logout func(provider string) error
LogoutProviderName func(provider string) string
// ExtRunner is the extension runner for emitting events from slash commands.
// May be nil in headless/test contexts; handlers must guard.
ExtRunner *inproc.Runner
// Skills is the loaded set of skill definitions for /skill listing.
Skills []*SkillDef
// contains filtered or unexported fields
}
SlashContext is the per-dispatch context handed to a handler. Accessor fields are populated by the host (interactive mode); handlers read them and write user-visible output via the `Append` sink. `Quit` is the requested-exit signal: only `/exit` and `/quit` set it. `Clear` is requested by `/clear` and `/new`.
type SlashHandler ¶
type SlashHandler func(sc *SlashContext) error
SlashHandler runs a builtin slash command. Handlers receive the SlashContext (which carries args + accessors + output sinks) and may return an error. A non-nil error causes the registry's Dispatch to surface "Error: <msg>" to the user.
type SlashRegistry ¶
type SlashRegistry struct {
// contains filtered or unexported fields
}
SlashRegistry holds builtins + extension-registered dynamic commands and resolves aliases. Concurrent-safe.
func NewSlashRegistry ¶
func NewSlashRegistry() *SlashRegistry
NewSlashRegistry seeds a registry with the built-in commands.
func (*SlashRegistry) All ¶
func (r *SlashRegistry) All() []SlashCommandInfo
All returns a sorted list of every command (builtin + extension) for /help rendering.
func (*SlashRegistry) Dispatch ¶
func (r *SlashRegistry) Dispatch(sc *SlashContext, line string, extCtx *ExtensionContext) error
Dispatch parses a line like `/foo bar baz` and routes it. Returns ErrUnknownSlashCommand if the command is not registered (the caller should forward the text to the LLM). Returns other errors if the handler failed. The host is responsible for surfacing errors to the user: Dispatch itself does not call sc.Append for errors.
extCtx is the bridge to extension-registered commands (which take a different handler signature). May be nil if no extensions are loaded.
func (*SlashRegistry) Register ¶
func (r *SlashRegistry) Register(cmd BuiltinSlashCommand)
Register adds (or replaces) a builtin and its aliases. Used both internally for the seed list and externally if a host wants to inject extra builtins (tests do this).
func (*SlashRegistry) ReplaceDynamic ¶
func (r *SlashRegistry) ReplaceDynamic(cmds []SlashCommand)
ReplaceDynamic replaces every extension-registered slash command with cmds, so a command whose extension is no longer loaded stops resolving.
type StandaloneReceipt ¶
type StandaloneReceipt struct {
Kind string
ExecutablePath string
PigVersion string
SHA256 string
UpdateSource string
UpdateTransportCA string
}
StandaloneReceipt binds a standalone install to the exact executable, release, update source, and installed bytes. The installer writes this owner-only receipt; Pig only validates it.
type StartupUIOptions ¶
type StatusLine ¶
type StatusLine struct {
tui.BaseComponent
// contains filtered or unexported fields
}
StatusLine is the rich footer rendered at the bottom of the interactive viewport. Renders as two lines matching upstream pi's FooterComponent (footer.ts):
Line 1: ~/<pwd> (<branch>) • <session-name> Line 2: ↑<in> ↓<out> $<cost> <context%>/<window> (auto) <model> • <thinking>
Color coding on the context-% column (upstream thresholds):
<=70% default (no color) >70% yellow (warning) >90% red (error)
All inputs are read on every Render() so the line reflects live state.
func NewStatusLine ¶
NewStatusLine creates a StatusLine bound to the given model + agent. timings may be nil; cost/elapsed columns are then suppressed.
func (*StatusLine) Flash ¶
func (s *StatusLine) Flash(msg string, ttl time.Duration)
Flash forwards status text to the interactive-mode chat status sink. The ttl argument is retained so existing callers do not need to change, but upstream-style status lines are not time-based footer overlays.
func (*StatusLine) GetExtensionStatuses ¶
func (s *StatusLine) GetExtensionStatuses() map[string]string
GetExtensionStatuses returns a snapshot of all extension statuses. Used by diagnostics and the footer renderer.
func (*StatusLine) GetHiddenThinkingLabel ¶
func (s *StatusLine) GetHiddenThinkingLabel() string
GetHiddenThinkingLabel returns the current hidden thinking label or "Thinking..." if not set.
func (*StatusLine) GetWorkingMessage ¶
func (s *StatusLine) GetWorkingMessage() string
GetWorkingMessage returns the current custom working message or "".
func (*StatusLine) GitBranch ¶
func (s *StatusLine) GitBranch() string
GitBranch returns the cached git branch, empty outside a repo.
func (*StatusLine) OnBranchChange ¶
func (s *StatusLine) OnBranchChange(fn func()) func()
OnBranchChange subscribes to git-branch updates. Returns an unsubscribe.
func (*StatusLine) ProviderCount ¶
func (s *StatusLine) ProviderCount() int
ProviderCount returns the number of authenticated, reachable providers.
func (*StatusLine) Render ¶
func (s *StatusLine) Render(width int) []string
Render returns the footer lines (normally 2 plus keyed statuses).
func (*StatusLine) ResetContextUsage ¶
func (s *StatusLine) ResetContextUsage()
ResetContextUsage clears the context-window column before a transcript rebuild re-reads it from the branch.
func (*StatusLine) SetAgentName ¶
func (s *StatusLine) SetAgentName(name string)
SetAgentName updates the agent persona label.
func (*StatusLine) SetAutoCompactEnabled ¶
func (s *StatusLine) SetAutoCompactEnabled(enabled bool)
SetAutoCompactEnabled updates the "(auto)" indicator.
func (*StatusLine) SetContextUsage ¶
func (s *StatusLine) SetContextUsage(tokens *int, contextWindow int)
SetContextUsage stores the Session projection estimate outside the render path. Nil tokens indicate unknown usage after compaction until a valid response.
func (*StatusLine) SetCwd ¶
func (s *StatusLine) SetCwd(cwd string)
SetCwd sets the working directory shown in the footer and resolves the git branch. Call once at init.
func (*StatusLine) SetExtensionStatus ¶
func (s *StatusLine) SetExtensionStatus(key, text string)
SetExtensionStatus sets (or clears) a keyed status entry in the footer's extension-status line. Mirrors upstream footer-data-provider.ts setStatus. Pass empty text to remove the key.
func (*StatusLine) SetHiddenThinkingLabel ¶
func (s *StatusLine) SetHiddenThinkingLabel(label string)
SetHiddenThinkingLabel sets the label for hidden thinking blocks. Pass empty to restore the default "Thinking...". Mirrors upstream setHiddenThinkingLabel (interactive-mode.ts:1635-1649).
func (*StatusLine) SetModel ¶
func (s *StatusLine) SetModel(m *ai.Model)
SetModel rebinds the model. Upstream footer.ts derives the subscription marker from the active model on every render, so a rebind re-evaluates it.
func (*StatusLine) SetName ¶
func (s *StatusLine) SetName(name string)
SetName updates the session name shown in the footer.
func (*StatusLine) SetProviderCount ¶
func (s *StatusLine) SetProviderCount(n int)
SetProviderCount updates the number of authenticated+reachable providers. When >1, the footer shows "(provider) model" instead of just "model". Mirrors upstream footer.ts:165-170.
func (*StatusLine) SetStatusHook ¶
func (s *StatusLine) SetStatusHook(fn func(string))
func (*StatusLine) SetSubscriptionResolver ¶
func (s *StatusLine) SetSubscriptionResolver(resolve func(*ai.Model) bool)
SetSubscriptionResolver installs the "(sub)" decision used by SetModel.
func (*StatusLine) SetSuppressedByExtFooter ¶
func (s *StatusLine) SetSuppressedByExtFooter(v bool)
SetSuppressedByExtFooter controls whether an extension-owned footer replaces the complete standard footer, including the keyed status row. The custom footer receives those statuses through FooterData and owns their rendering.
func (*StatusLine) SetThinkingLevel ¶
func (s *StatusLine) SetThinkingLevel(level string)
SetThinkingLevel updates the thinking level display.
func (*StatusLine) SetTurnContextUsage ¶
func (s *StatusLine) SetTurnContextUsage(u *ai.Usage)
SetTurnContextUsage records the latest usage for the context-window column. Token and cost totals come from the usage totals source instead.
func (*StatusLine) SetUsageTotalsSource ¶
func (s *StatusLine) SetUsageTotalsSource(source func() footerUsageTotals)
SetUsageTotalsSource installs the session usage totals read on each render.
func (*StatusLine) SetUsingSubscription ¶
func (s *StatusLine) SetUsingSubscription(v bool)
SetUsingSubscription updates the OAuth subscription indicator. When true, cost display shows "(sub)". Mirrors upstream footer.ts:128.
func (*StatusLine) SetWorking ¶
func (s *StatusLine) SetWorking(b bool)
SetWorking flips the spinner column on/off.
func (*StatusLine) SetWorkingMessage ¶
func (s *StatusLine) SetWorkingMessage(message string)
SetWorkingMessage sets a custom message shown during streaming. Pass empty to restore the default spinner. Mirrors upstream loadingAnimation.setMessage (interactive-mode.ts:1877-1885).
type StdinBuffer ¶
type StdinBuffer struct {
// contains filtered or unexported fields
}
StdinBuffer mirrors upstream packages/tui/src/stdin-buffer.ts. It accumulates partial escape sequences across reads so the input loop only sees complete chunks. Bracketed pastes are re-emitted as a single framed payload because dispatchKey/classifyKey currently consume the upstream ESC[200~...ESC[201~ form directly. The zero value uses upstream's default timeouts.
func NewStdinBuffer ¶
func NewStdinBuffer(options StdinBufferOptions) *StdinBuffer
NewStdinBuffer mirrors the upstream StdinBuffer constructor.
func (*StdinBuffer) Clear ¶
func (b *StdinBuffer) Clear()
func (*StdinBuffer) Flush ¶
func (b *StdinBuffer) Flush() []string
Flush emits any incomplete remainder as a single chunk. Mirrors upstream's timeout-based fallback path; the input loop owns the timer.
func (*StdinBuffer) FlushTimeout ¶
func (b *StdinBuffer) FlushTimeout() time.Duration
FlushTimeout is how long the buffered remainder waits for more input before Flush emits it: the escape timeout for a lone ESC, the sequence timeout for anything else. Mirrors the timeout StdinBuffer.process schedules upstream.
func (*StdinBuffer) HasPendingFlush ¶
func (b *StdinBuffer) HasPendingFlush() bool
func (*StdinBuffer) ProcessBytes ¶
func (b *StdinBuffer) ProcessBytes(data []byte) []string
ProcessBytes mirrors upstream process(Buffer): it feeds raw bytes and returns any complete keystroke chunks ready for dispatch. Terminal loops use ProcessTerminalBytes, which matches upstream's utf8-decoded stdin instead.
func (*StdinBuffer) ProcessString ¶
func (b *StdinBuffer) ProcessString(s string) []string
ProcessString mirrors upstream process(string).
func (*StdinBuffer) ProcessTerminalBytes ¶
func (b *StdinBuffer) ProcessTerminalBytes(data []byte) []string
ProcessTerminalBytes feeds one terminal read. It decodes UTF-8 across reads the way upstream ProcessTerminal's stdin.setEncoding("utf8") does, so a character split between reads is held until it is complete and a lone high byte is never rewritten as a Meta key; the decoded text then goes through ProcessString.
type StdinBufferOptions ¶
type StdinBufferOptions struct {
// Timeout is how long an incomplete escape sequence waits for more input.
Timeout time.Duration
// EscapeTimeout is how long a lone ESC waits before it is the Escape key.
EscapeTimeout time.Duration
}
StdinBufferOptions mirrors upstream StdinBufferOptions. A zero field keeps the upstream default.
type SteppedSubmenu ¶
type SteppedSubmenu struct {
// contains filtered or unexported fields
}
SteppedSubmenu selects dependent values, goes back one step on Escape, and optionally loops after completion.
func NewSteppedSubmenu ¶
func NewSteppedSubmenu(steps []SteppedSubmenuStep, onComplete func(map[string]string), onCancel func(), opts SteppedSubmenuOptions) *SteppedSubmenu
func (*SteppedSubmenu) HandleInput ¶
func (s *SteppedSubmenu) HandleInput(data string)
func (*SteppedSubmenu) Invalidate ¶
func (s *SteppedSubmenu) Invalidate()
func (*SteppedSubmenu) Render ¶
func (s *SteppedSubmenu) Render(width int) []string
type SteppedSubmenuOptions ¶
type SteppedSubmenuOptions struct {
}
SteppedSubmenuOptions controls the initial step and completion behavior.
type SteppedSubmenuStep ¶
type SteppedSubmenuStep struct {
}
SteppedSubmenuStep resolves its title, description, and options from earlier selections. Functions represent both constant and context-dependent upstream strings.
type SubprocessHost ¶
type SubprocessHost interface {
Reload(ctx context.Context) ([]extension.Extension, error)
ExtensionCount() int
LastReloadReport() *subprocess.ReloadReport
LoadErrors() []string
SetWidthFunc(fn func() int)
SetHeightFunc(fn func() int)
NotifyWidth(width int)
NotifyHeight(height int)
SetCrashHandler(fn func(name string, delay time.Duration, disabled bool, reason string))
IsShuttingDown() bool
}
SubprocessHost is the interface for managing subprocess extension lifecycle during reload. Satisfied by *subprocess.Host.
pig-specific: no upstream equivalent.
type SubprocessUIBridge ¶
type SubprocessUIBridge interface {
SetInvalidate(fn func())
SetNotifyFunc(fn func(message, level string))
SetUIContext(ctx extension.UIContext)
// SetUIPromptScope binds the runner that reports subprocess ui_prompt_start
// and ui_prompt_end events.
SetUIPromptScope(scope subprocess.UIPromptScope)
// SetHostAction sets a named host callback. Known keys:
// "getFlag", "getActiveTools", "getAllTools", "getCommands", "getThinkingLevel",
// "setThinkingLevel", "getContextUsage", "getSystemPrompt", "isIdle",
// "abort", "hasPendingMessages", "shutdown", "waitForIdle", "reload",
// "sendUserMessage", "getSessionName", "setSessionName", "setLabel".
SetHostAction(key string, fn any)
PublishModelCatalog()
// SetWidgetSyncFunc sets a callback invoked whenever an extension sets
// or clears a widget. The callback receives all current widget proxies
// as *subprocess.PushProxy values (keyed by "extName:widgetKey").
SetWidgetSyncFunc(fn func(widgets map[string]*subprocess.PushProxy))
}
SubprocessUIBridge is the interface satisfied by *subprocess.UIBridge for wiring subprocess extension UI after TUI creation.
pig-specific: no upstream equivalent.
type TUIUIContext ¶
type TUIUIContext struct {
// NotifyFunc receives styled notification text when no interactive mode is attached.
NotifyFunc func(message string)
// contains filtered or unexported fields
}
TUIUIContext implements ExtensionUIContext for interactive mode.
func NewTUIUIContext ¶
func NewTUIUIContext(t tui.Renderer) *TUIUIContext
NewTUIUIContext creates a TUI-backed ExtensionUIContext.
func (*TUIUIContext) Confirm ¶
func (u *TUIUIContext) Confirm(title, message string) bool
func (*TUIUIContext) Notify ¶
func (u *TUIUIContext) Notify(message, level string)
func (*TUIUIContext) Select ¶
func (u *TUIUIContext) Select(title string, options []string) (string, bool)
func (*TUIUIContext) SetStatus ¶
func (u *TUIUIContext) SetStatus(key, text string)
func (*TUIUIContext) SetWidget ¶
func (u *TUIUIContext) SetWidget(key string, lines []string)
type ThinkingBudgetsSettings ¶
type ThinkingBudgetsSettings struct {
Minimal *int `json:"minimal,omitempty"`
Low *int `json:"low,omitempty"`
Medium *int `json:"medium,omitempty"`
High *int `json:"high,omitempty"`
}
ThinkingBudgetsSettings mirrors upstream ThinkingBudgetsSettings. Custom token budgets for each thinking level. Mirrors upstream settings-manager.ts ThinkingBudgetsSettings.
type ThinkingLevelEntry ¶
type ThinkingLevelEntry struct {
SessionEntryBase
ThinkingLevel string `json:"thinkingLevel"`
}
ThinkingLevelEntry records a user-initiated thinking level change (Shift+Tab). Mirrors upstream appendThinkingLevelChange in agent-session.ts. Persisted as type="thinking_level_change" so the session tree can display [thinking: level].
type ThinkingSelectorComponent ¶
ThinkingSelectorComponent renders the /thinking selector: a search input over the available levels, the current level marked with a check, the saved default annotated, and app.thinking.save to save the highlighted level as the default. Ports upstream components/thinking-selector.ts.
func NewThinkingSelectorComponent ¶
func NewThinkingSelectorComponent( currentLevel string, availableLevels []string, onSelect func(level string), onCancel func(), onSelectAsDefault func(level string), defaultThinkingLevel string, ) *ThinkingSelectorComponent
NewThinkingSelectorComponent builds the selector. onSelectAsDefault may be nil, which disables the save binding; defaultThinkingLevel annotates that level's description.
func (*ThinkingSelectorComponent) GetSelectList ¶
func (s *ThinkingSelectorComponent) GetSelectList() *tui.FilterableList
GetSelectList returns the level list, as upstream getSelectList.
func (*ThinkingSelectorComponent) HandleInput ¶
func (s *ThinkingSelectorComponent) HandleInput(data string)
HandleInput routes a key: the save binding saves the highlighted level as the default, navigation keys drive the list, and everything else edits the search query.
type TierError ¶
type TierError struct {
Tier SelfUpdateTier
ExePath string
Remediation string
Cause error
}
TierError reports that tier resolution could not select exactly one owner, or that the selected tier refused mutation. It carries the executable path and a concrete, non-looping remediation so the caller surfaces it verbatim.
type ToolCallEventResult ¶
type ToolCallEventResult struct {
Block bool `json:"block"`
Reason string `json:"reason,omitempty"`
}
ToolCallEventResult controls whether an extension allows a tool call.
type TrailingEntries ¶
TrailingEntries builds export-only entries appended after the branch. It receives the last branch entry ID (nil for an empty branch) and the export timestamp. Mirrors upstream TrailingEntries.
type UpdateBinary ¶
UpdateBinary is one platform's download URL and expected SHA256 (hex).
type UpdateManifest ¶
type UpdateManifest struct {
Version string `json:"version"`
PackageName string `json:"packageName"`
Notes string `json:"notes,omitempty"`
Binaries map[string]UpdateBinary `json:"binaries"`
}
UpdateManifest is the document an update source returns: the latest version plus a per-platform binary URL and checksum. Host-agnostic so any static host or marketplace can serve it. Binaries is keyed by "<goos>/<goarch>".
func FetchUpdateManifest ¶
func FetchUpdateManifest(ctx context.Context, client *http.Client, rawURL string) (*UpdateManifest, error)
FetchUpdateManifest reads, authenticates, and parses the exact update manifest at rawURL.
func (*UpdateManifest) PlatformBinary ¶
func (m *UpdateManifest) PlatformBinary() (UpdateBinary, bool)
PlatformBinary returns the manifest's binary for the current platform.
type UsageEntry ¶
type UsageEntry struct {
SessionEntryBase
// Kind is an arbitrary usage category, such as "cache_warm".
Kind string `json:"kind"`
Provider string `json:"provider"`
Model string `json:"model"`
Usage ai.Usage `json:"usage"`
// Note is an optional human-readable qualifier for usage notices.
Note string `json:"note,omitempty"`
}
UsageEntry is model-attributed usage that does not enter LLM context, such as a cache-warming refresh. Mirrors upstream session-manager.ts UsageEntry.
type WarningSettings ¶
type WarningSettings struct {
AnthropicExtraUsage bool `json:"anthropicExtraUsage,omitempty"`
// contains filtered or unexported fields
}
WarningSettings mirrors upstream warning settings.
func (WarningSettings) MarshalJSON ¶
func (w WarningSettings) MarshalJSON() ([]byte, error)
func (*WarningSettings) UnmarshalJSON ¶
func (w *WarningSettings) UnmarshalJSON(data []byte) error
Source Files
¶
- agent_boundary.go
- auth_filter.go
- auth_guidance.go
- auth_warnings.go
- auto_recovery.go
- bash_executor.go
- bug_report.go
- bug_report_unix.go
- cache_stats.go
- cache_warmer.go
- changelog.go
- chat_viewport.go
- clipboard.go
- clipboard_copy.go
- clipboard_paste.go
- clipboard_text.go
- context_files.go
- crash_log.go
- custom_message_route.go
- custom_overlay.go
- defaults.go
- event_bridge.go
- experimental.go
- ext_ui_context.go
- extension_conflicts.go
- extensions.go
- external_editor.go
- external_editor_unix.go
- file_lock.go
- file_processor.go
- git_watcher.go
- image_convert.go
- images.go
- install_telemetry.go
- interactive.go
- interactive_auth.go
- interactive_bug.go
- interactive_cache_warming.go
- interactive_chat.go
- interactive_commands.go
- interactive_crash.go
- interactive_editor.go
- interactive_events.go
- interactive_extension_errors.go
- interactive_extensions.go
- interactive_helpers.go
- interactive_input.go
- interactive_layout.go
- interactive_llama.go
- interactive_models.go
- interactive_share.go
- interactive_signals_unix.go
- interactive_status.go
- interactive_thinking.go
- interactive_tools_status.go
- interactive_transcript.go
- interactive_tree.go
- interactive_tui.go
- interactive_turn.go
- keybindings.go
- keys.go
- kitty_csi.go
- login_header.go
- markdown_transform.go
- mermaid_transform.go
- migrations.go
- model_catalog_refresh.go
- model_input_limits.go
- model_picker.go
- model_registry.go
- model_registry_runtime_models.go
- output_guard.go
- parity_harness.go
- paths.go
- prompt_diagnostics.go
- prompt_images.go
- prompt_templates.go
- radius.go
- radius_composition.go
- radius_models.go
- reload_resources.go
- request_auth_runtime.go
- resource_source_info.go
- resources.go
- selfupdate.go
- selfupdate_receipt.go
- selfupdate_tier.go
- selfupdate_tier_unix.go
- session.go
- session_export.go
- session_handle.go
- session_manager.go
- session_manager_projection.go
- session_resume.go
- session_selector.go
- session_selectors.go
- session_share.go
- session_stats.go
- settings.go
- settings_diagnostics.go
- settings_selector.go
- settings_submenu.go
- skills.go
- slash_bug.go
- slash_commands.go
- slash_helpers.go
- slash_session_handlers.go
- startup_header.go
- startup_hints.go
- startup_ui.go
- status_line.go
- stdin_buffer.go
- terminal_input_queue.go
- thinking_selector.go
- tmux_check.go
- tool_render.go
- tool_render_list.go
- tool_render_shell.go
- tool_result_content.go
- tree_row_format.go
- trust_manager.go
- windows_self_update.go
- windows_self_update_other.go
- wsl.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Branch summarization for tree navigation.
|
Branch summarization for tree navigation. |
|
Package export provides HTML session export.
|
Package export provides HTML session export. |
|
Package frontmatter parses YAML frontmatter blocks from markdown files.
|
Package frontmatter parses YAML frontmatter blocks from markdown files. |
|
Package llama ports Pi's built-in llama.cpp extension (packages/coding-agent/src/extensions/llama/): the router HTTP/SSE client, Hugging Face search and download, the dynamic provider, the manager UI, and the /llama command.
|
Package llama ports Pi's built-in llama.cpp extension (packages/coding-agent/src/extensions/llama/): the router HTTP/SSE client, Hugging Face search and download, the dynamic provider, the manager UI, and the /llama command. |
|
Package prompts builds the default coding-agent system prompt.
|
Package prompts builds the default coding-agent system prompt. |
|
tools/bash_executor.go: user bash execution (!cmd, RPC bash, SDK ExecuteBash).
|
tools/bash_executor.go: user bash execution (!cmd, RPC bash, SDK ExecuteBash). |