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 can ModelRuntime compose". Reachable is the whole built-in catalog plus ollama; authenticated is the subset whose credentials resolve from the environment, models.json, or auth.json.
Used by the interactive model surfaces (cycleModel, showScopedModels, --list-models) to default the picker scope to {auth ∩ reachable}.
Mirrors upstream pi-coding-agent's model-runtime.ts availability filter: upstream derives `available` from checkAuth() over the whole provider catalog, so pig derives both sets from the catalog rather than a hand-maintained provider list.
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.
Ports packages/coding-agent/src/core/resource-loader.ts
pig-specific: conversions the host-owned ModelRuntime of the session graph (coding/session_graph_model_runtime.go) needs from this package's extension wire code.
extensions.go defines extension event names and the TUI-backed UI surface:
- Event name constants
- ToolCallEventResult (agent loop hook)
- ExtensionContext (shared mutable state for the agent loop)
- SlashCommand type (used by slash_commands.go)
- TUIUIContext (interactive mode UI)
Ports packages/coding-agent/src/cli/file-processor.ts.
Ports packages/coding-agent/src/modes/interactive/interactive-mode.ts.
Ports packages/coding-agent/src/core/model-runtime.ts
Ports packages/coding-agent/src/core/provider-composer.ts
Ports packages/coding-agent/src/core/model-runtime.ts
Ports packages/coding-agent/src/modes/interactive/interactive-mode.ts
Ports packages/coding-agent/src/modes/interactive/tui-renderer.ts.
Ports packages/coding-agent/src/core/model-runtime.ts Ports packages/coding-agent/src/core/provider-composer.ts
Ports packages/coding-agent/src/core/package-manager.ts (addAutoDiscoveredResources, collectAncestorAgentsSkillDirs, getHomeDir) and the ambient resource ordering of packages/coding-agent/src/core/resource-loader.ts reload.
Ports packages/coding-agent/src/config.ts (getConfiguredSelfUpdateArgv, makeConfiguredSelfUpdateCommand), Pi 8bc94b19.
Ports packages/coding-agent/src/config.ts
Ports packages/coding-agent/src/config.ts (detectInstallMethod, getInferredNpmInstall; the native ownership tier is D39).
Ports packages/coding-agent/src/modes/interactive/components/session-selector.ts.
Ports packages/coding-agent/src/modes/interactive/components/session-selector.ts (deleteSessionFile).
Ports packages/coding-agent/src/modes/interactive/components/session-selector.ts (deleteSessionFile).
Ports packages/coding-agent/src/modes/interactive/components/session-selector.ts.
Ports packages/coding-agent/src/modes/interactive/components/settings-selector.ts
Ports packages/coding-agent/src/modes/interactive/components/settings-selector.ts (fullscreen-wheel-scroll-lines row).
Ports packages/coding-agent/src/core/skills.ts.
Ports packages/coding-agent/src/modes/interactive/interactive-mode.ts.
Ports packages/coding-agent/src/modes/interactive/interactive-mode.ts
Ports packages/coding-agent/src/core/tools/renderers/index.ts.
Index ¶
- Constants
- Variables
- func ActiveExtensionTheme() extension.Theme
- func ActiveExtensionThemeWire() extension.Theme
- func AgentDir() string
- func AgentDirConfigured() bool
- func AgentEventContext(ev agent.AgentEvent) context.Context
- func AgentLoopEventType(ev agent.AgentEvent) string
- func AgentStateSystemPrompt(messages []agent.AgentMessage) string
- func AmbientPromptPaths(cwd, agentDir string, sm *SettingsManager, project bool) []string
- func AmbientSkillPaths(cwd, agentDir string, sm *SettingsManager, project, user bool) []string
- func AmbientSkillPathsIn(scan *AgentsSkillScan, cwd, agentDir string, sm *SettingsManager, ...) []string
- func ApplyToolModifiers(base, entries []string) []string
- func AreExperimentalFeaturesEnabled() bool
- func AssertSessionCwdExists(session *Session, fallbackCwd string) error
- func AuthResultJSON(result *ai.AuthResult) map[string]any
- func AuthenticatedProviders(agentDir string) map[string]bool
- func BeforeExit()
- func BeginSessionMarker(agentDir, version, cwd string)
- func BindAppendEntryAction(bridge HostActionBinder, current func() (*Session, error), ...)
- func BugReportArchiveFileName(id string) string
- func BugReportIssueLink(metadata BugReportMetadata, archiveName, upstreamVersion string) string
- func CanonicalizePath(path string) string
- func CatalogRoot(agentDir string) string
- func ChalkApply(open, closeSeq, text string) string
- func ChalkColorLevel(args []string, getenv func(string) string, lookup func(string) (string, bool), ...) int
- func CleanupWindowsSelfUpdateQuarantine(packageDir string)
- func ClearCrashLog(path string)
- func CompareChangelogEntries(a, b ChangelogEntry) int
- func ComparePackageVersions(left, right string) (int, bool)
- func ConfigDirName() string
- func ConfigRoot() string
- func ConfiguredSelfUpdateArgv(setting []string) []string
- func ContainerRemediation(exePath string) string
- func ContextFilesWithheldMessage(paths []string) string
- func ConvertImageBytesToPng(data []byte) []byte
- func ConvertToPng(base64Data, mimeType string) *tui.ConvertedImage
- func CopyToClipboard(text string) error
- func CrashLogPath(agentDir string) string
- func CrashOutputDir(agentDir string) string
- func CreateAllToolRenderers() map[string]ToolRenderers
- func CreateInteractiveTui(options InteractiveTuiOptions) tui.TUI
- func CreateShareTrailingEntries(state ShareState, parentID *string, timestamp string) []any
- func CurrentSystemMessage(messages []agent.AgentMessage) *ai.SystemMessage
- func DefaultAgentDir() string
- func DefaultModelPerProvider() map[string]string
- func DefaultSkillsDir() string
- func DefaultToolNames() []string
- func DetectSupportedImageMimeType(data []byte) string
- func DiscoverAncestorAgentsSkillDirs(startDir string) []string
- func DiscoverPromptFile(cwd, agentDir, name string, projectTrusted bool) string
- func DispatchAgentLoopEvent(runner *inproc.Runner, ev agent.AgentEvent, ...)
- func EarlyModelStream(transport ai.Transport) ...
- func EndSessionMarker()
- func EnsureSessionDir(dir string) error
- func ExitLogPath(agentDir string) string
- func ExpandPromptTemplate(line string, templates []PromptTemplate) (string, bool)
- func ExpandSkillCommand(text string, skills []*SkillDef) (string, bool, *extension.ExtensionError)
- func ExpandTildePath(path string) string
- func ExportFileToHTML(inputPath, outputPath string) (string, error)
- func ExportSessionForShare(filePath string, session *Session, state ShareState) (string, error)
- func ExportSessionToHTML(sessionFile, outputPath string, ...) (string, error)
- func ExportSessionToJsonl(session *Session, outputPath string, createTrailingEntries TrailingEntries) (string, error)
- func ExportThemeName(candidates ...string) string
- func ExportToolRenderers(runner *inproc.Runner) func(name string) *extension.ToolRenderers
- func ExtensionEntryIdentity(sess *Session, direct *subprocess.DirectEntryAppend) (string, string, error)
- func ExtensionForImageMIME(mime string) string
- func ExtensionModelRegistryState(registry *ModelRegistry, catalog []*ai.Model) map[string]any
- func ExtensionPackageRoot(origin, source, baseDir string) string
- func ExtensionSessionDir(override string) string
- func ExtensionSessionInfo(view ExtensionSessionView) map[string]any
- func ExtensionSessionRead(view ExtensionSessionView, method string, args json.RawMessage) (any, error)
- func ExtensionThemePalette(theme *tui.Theme) extension.Theme
- func ExtensionToolInfos(runner ExtensionToolLister, allowed, excluded map[string]struct{}) []subprocess.ToolInfo
- func ExtensionToolInfosScoped(runner ExtensionToolLister, allowed, excluded map[string]struct{}, ...) []subprocess.ToolInfo
- func ExtensionsInLoadOrder(configured, builtins []extension.Extension) []extension.Extension
- func ExtensionsInLoadOrderWithExplicit(configured, builtins []extension.Extension, explicit []string) []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 FormatMissingSessionCwdError(issue SessionCwdIssue) string
- func FormatMissingSessionCwdPrompt(issue SessionCwdIssue) string
- func FormatNoAPIKeyFoundMessage(provider string) string
- func FormatNoModelSelectedMessage() string
- func FormatNoModelsAvailableMessage() string
- func FormatPathRelativeToCwdOrAbsolute(filePath, cwd string) string
- func FormatTokens(n int) string
- func GenerateSessionID() (string, error)
- func GetCacheWarmingDelayMs(ttlMs float64) (float64, bool)
- func GetCwdRelativePath(filePath, cwd string) string
- func GetDefaultSessionDirPath(cwd, agentDir string) string
- func GetDocsPath() string
- func GetExamplesPath() string
- func GetPackageDir() string
- func GetProjectTrustParentPath(cwd string) string
- func GetProjectTrustPath(cwd string) string
- func GetPromptCacheTtlMs(model *ai.Model, options ai.StreamOptions) (float64, bool)
- func GetRadiusGatewayURL() string
- func GetReadmePath() string
- func GetToolListError(entries []string) string
- func GitInstallRoot(cwd, agentDir string, project bool) string
- func GraphAPIModel(raw json.RawMessage) (*ai.Model, error)
- func GraphClassify(ctx context.Context, ...) json.RawMessage
- func GraphGenerateImages(ctx context.Context, ...) json.RawMessage
- func GraphMessages(raw json.RawMessage) ([]ai.Message, error)
- func GraphModelStreamRequest(ctx context.Context, model *ai.Model, request map[string]any, ...) (context.Context, ai.Context, ai.StreamOptions, error)
- func GraphProjectTrustStoreStatic(_ context.Context, method string, raw json.RawMessage) (any, error)
- func GraphProviderConfig(input *ProviderConfigInput) (map[string]any, error)
- func GraphSessionManagerStatic(ctx context.Context, scope subprocess.SessionGraphScope, method string, ...) (any, error)
- func HasProjectContextFile(cwd string) bool
- func HasTrustRequiringProjectResources(cwd string) bool
- func HiddenToolNames(hidden map[string]struct{}) []string
- func ImmutableBinaryRemediation(exePath string) string
- func InvokeProviderStreamSimple(ctx context.Context, id string, callback extension.ProviderStreamSimple, ...) (stream *ai.AssistantMessageEventStream, err error)
- func IsContextOverflow(msg *agent.AssistantMessage, contextWindow int) bool
- func IsLocalPath(value string) bool
- func IsNewerPackageVersion(candidate, current string) 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 IsSyntheticPath(path string) bool
- func IsToolModifier(entry string) bool
- func IsWSL(getenv func(string) string, readFile func(string) ([]byte, error)) bool
- func KeyIDPattern() string
- func KeybindingsFile(agentDir string) string
- func KeybindingsSchemaArtifact() configschema.Artifact
- func LastLeaf() *string
- func ListSkills(skillsDir string) ([]string, error)
- func LoadExtensionTheme(name *string) any
- func MarkPathIgnoredByCloudSync(path string)
- func MigrateSessionEntries(entries []FileEntry) error
- func MkdirSessionDir(dir string) error
- func ModelNetworkEnabled() bool
- func NPMInstallRoot(cwd, agentDir string, project bool) string
- func NewEditorWithOptions(options CustomEditorOptions, editorOptions ...tui.EditorOption) *tui.Editor
- func NewTreeSelectorComponent(tree []*SessionTreeNode, currentLeafID *string, terminalHeight int, ...) *tui.TreeSelectorComponent
- func NormalizeChangelogLinks(markdown, version string) string
- func NormalizeExtensionPaths(cwd string, paths *extension.ResourcesDiscoverAggregateResult) (*extension.ResourcesDiscoverAggregateResult, error)
- func NormalizePromptContent(content []ai.UserContentBlock, autoResize bool, model *ai.Model, ...) []ai.UserContentBlock
- func NormalizeToolResultImages(result agent.AgentToolResult, autoResize bool) agent.AgentToolResult
- func OpenBrowser(target string)
- func OpenExternalEditor(ctx context.Context, initial string, configuredEditor string) (string, error)
- func PackageManagerHomeDir() (string, error)
- func ParsePromptArgs(s string) []string
- func PigDocsFile(name string) (path string, ok bool)
- func PigletArtifactsDir() string
- func PigletRecordsDir() string
- func PigletsDir() string
- func PlatformKey() string
- func PngTranscoder(base64Data, _ string) (string, bool)
- func PrepareWindowsNpmSelfUpdate(ctx context.Context, exePath string) error
- func ProjectConfigDir(cwd string) string
- func ProjectContextEntry(entry SessionEntry, messages []agent.AgentMessage, edit *ContextEditEntry) []agent.AgentMessage
- func ProjectStateDir(cwd, namespace string) string
- func ProviderLoginHelp() string
- func QuarantineWindowsNativeDependencies(ctx context.Context, 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 ReadExitLogTail(agentDir string, n int) []string
- func ReadNativeProviderModelData(r *ModelRegistry)
- func ReadStoredCredentialEntry(providerID, authPath string) json.RawMessage
- func ReadStoredCredentialEntryAt(providerID, authPath string) json.RawMessage
- func RealPathSync(path string) (string, error)
- func ReconcileSessionMarkers(agentDir string, now time.Time)
- func RecordEnding(agentDir, reason string) bool
- func RecordExit(agentDir, reason string)
- func RecoverUncaught()
- func RedactBugReportJSON(value any) (any, error)
- func RedactBugReportURL(value string) string
- func RemoteMouseEvent(event tui.TuiMouseEvent) extension.RemoteMouseEvent
- func RenderLoginHeader(definition extension.ValidatedLoginDefinition, width int, ...) []string
- func RenderTreeASCII(root *SessionTreeNode) string
- func ReportDiagnostics(diagnostics []AgentSessionRuntimeDiagnostic)
- func ResolveAgentDir() (string, error)
- func ResolveDefaultAgentDir() (string, error)
- func ResolvePath(input, baseDir string) (string, error)
- func ResolvePromptInput(input, description string) string
- func ResourcePathKey(path string) string
- func ResourcePaths(resources []ResolvedResource) []string
- func ResourcePrecedenceRank(metadata PathMetadata) int
- func ResourcesDiscoverReason(sessionStartReason string) string
- func RestoreStdout()
- func RunConfiguredSelfUpdateCommand(ctx context.Context, cmd *SelfUpdateCommand) 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(SessionListOptions) ([]SessionInfo, error), ...) (path string, selected bool, err 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 SetUncaughtGoroutineHandler(handler func(value any, stack []byte)) (restore func())
- func SettingsFileExists(agentDir string) bool
- 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 SignalName(sig os.Signal) string
- func SkillDiagnostics(skill *SkillDef) []string
- func StartupKeybindHints(km *KeybindingsManager) string
- func StateDir(namespace string) string
- func StreamAPILeaf(ctx context.Context, simple bool, model, request map[string]any, ...) (*ai.AssistantMessageEventStream, error)
- func SubstitutePromptArgs(content string, args []string) string
- func SyntheticPathSource(path string) string
- func SystemMessageFromAgentMessage(message agent.AgentMessage) (ai.SystemMessage, bool)
- func SystemPromptSkills(skills []*SkillDef) []extension.SystemPromptSkill
- func TakeOverStdout() error
- func ToolExecutionResultOf(result agent.AgentToolResult, elapsed time.Duration) tui.ToolResultUpdate
- func ToolResultEventContent(result agent.AgentToolResult) []any
- func ToolResultEventOverride(result *extension.ToolResultEventResult) agent.AfterToolCallResult
- func TopLevelResourcePaths(autoDir string, entries []string, kind packagecontent.Kind) []string
- func UnsupportedRemediation(exePath string) string
- func UpdateSourceURL() string
- func UsePiDirs() bool
- func ValidateAutoDiscoveredOverrides(cwd, agentDir string, sm *SettingsManager, projectTrusted bool) error
- func WireEarlyModelStream(bridge ModelOperationBridge, transport ai.Transport)
- func WireModelOperations(bridge ModelOperationBridge, bindings ModelOperationBindings) func()
- func WithPersonalizedCatalog(provider *ai.ModelsProvider, personalize PersonalizeCatalog, ...) *ai.ModelsProvider
- func WithRemoteCatalog(provider *ai.ModelsProvider, catalogBaseURL string, localGeneratedAt *float64) *ai.ModelsProvider
- func WithheldProjectContextFiles(cwd, agentDir string) []string
- func WriteBugReportArchive(bundle BugReportBundle, path string) (err error)
- func WriteRawStdout(text string) (int, error)
- func WriteStandaloneReceipt(exe, version, source string) error
- type AgentSessionRuntimeDiagnostic
- type AgentsSkillDir
- type AgentsSkillScan
- type AppKeybinding
- type ArminComponent
- type BashExecOptions
- type BashExecutionEntry
- type BashExecutionMessage
- type BashResult
- type BeforeAgentStartRun
- func (r BeforeAgentStartRun) BaseSections(selectedTools []string, hidden map[string]struct{}) ai.OrderedSections
- func (r BeforeAgentStartRun) NextTurnOptions(base extension.BuildSystemPromptOptions) extension.BuildSystemPromptOptions
- func (r BeforeAgentStartRun) PromptSections(selectedTools []string, hidden map[string]struct{}) (ai.OrderedSections, error)
- type BinaryUpdate
- type BlockedStatus
- 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 CodemodeMode
- type CodemodeSettings
- type CommandCatalogVersion
- type CompactionConfig
- type CompactionEntry
- type CompactionModelOverride
- type CompactionResult
- type CompactionSettingsJSON
- type CompatibilityRequestConfig
- type ContextEditEntry
- type ContextEditReplacement
- type ContextEditableContent
- type ContextFile
- type CrashInput
- type CrashRecord
- type CredentialSynchronizationError
- type CredentialSynchronizationOperation
- type CustomEditor
- type CustomEditorOptions
- type CustomEntry
- type CustomEntryComponent
- func (c *CustomEntryComponent) HasContent() bool
- func (c *CustomEntryComponent) Invalidate()
- func (c *CustomEntryComponent) IsDirty() bool
- func (c *CustomEntryComponent) SetExpanded(expanded bool)
- func (c *CustomEntryComponent) SetOutputPad(outputPad int)
- func (c *CustomEntryComponent) SurfaceLive() bool
- type CustomMessageEntry
- type DefaultProjectTrust
- type ExtUIContext
- func (u *ExtUIContext) AddAutocompleteProvider(factory extension.AutocompleteProviderFactory) error
- func (u *ExtUIContext) AddAutocompleteProviderWithLifetime(lifetime context.Context, factory extension.AutocompleteProviderFactory) error
- func (u *ExtUIContext) AutocompleteProvider(ctx context.Context) (*extension.AutocompleteProvider, error)
- func (u *ExtUIContext) Bell()
- func (u *ExtUIContext) ClearHiddenThinkingLabel()
- func (u *ExtUIContext) ClearWorkingMessage()
- func (u *ExtUIContext) Confirm(ctx context.Context, title, message string, ...) (bool, error)
- func (u *ExtUIContext) Custom(ctx context.Context, factory extension.CustomFactory, ...) (any, error)
- func (u *ExtUIContext) Editor(ctx context.Context, title, prefill string) (string, error)
- func (u *ExtUIContext) GetAllThemes() []extension.ThemeMeta
- func (u *ExtUIContext) GetEditorComponent() extension.EditorFactory
- func (u *ExtUIContext) GetEditorText() string
- func (u *ExtUIContext) GetTheme(name string) (extension.Theme, error)
- func (u *ExtUIContext) GetToolsExpanded() bool
- func (u *ExtUIContext) HideTopOverlay(ctx context.Context) (any, error)
- 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) RegisterSprite(owner string, definition extension.ValidatedSpriteDefinition) error
- 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 extension.EditorFactory)
- func (u *ExtUIContext) SetEditorText(text string)
- func (u *ExtUIContext) SetFooter(factory extension.FooterFactory)
- func (u *ExtUIContext) SetHeader(factory extension.HeaderFactory)
- func (u *ExtUIContext) SetHiddenThinkingLabel(label string)
- func (u *ExtUIContext) SetLogin(definition extension.LoginDefinition) error
- func (u *ExtUIContext) SetRemoteFocus(ctx context.Context, target extension.RemoteOverlayFocusTarget) (any, error)
- func (u *ExtUIContext) SetStatus(key, text string)
- func (u *ExtUIContext) SetTheme(selection extension.ThemeSelection) extension.SetThemeResult
- func (u *ExtUIContext) SetTitle(title string)
- func (u *ExtUIContext) SetToolsExpanded(expanded bool)
- func (u *ExtUIContext) SetWidget(key string, content []string, opts *extension.ExtensionWidgetOptions)
- func (u *ExtUIContext) SetWidgetFactory(key string, factory extension.WidgetFactory, ...)
- func (u *ExtUIContext) SetWorkingIndicator(options extension.WorkingIndicatorOptions)
- func (u *ExtUIContext) SetWorkingMessage(message string)
- func (u *ExtUIContext) SetWorkingVisible(visible bool)
- func (u *ExtUIContext) ShowRemoteOverlay(opts extension.RemoteOverlayOptions, host extension.RemoteOverlayHost) (extension.RemoteOverlayHandle, <-chan struct{}, bool)
- func (u *ExtUIContext) Theme() extension.Theme
- func (u *ExtUIContext) UnregisterSprites(owner string)
- type ExtensionCommandLister
- type ExtensionConflict
- type ExtensionContext
- type ExtensionEditorComponent
- type ExtensionEditorOptions
- type ExtensionOAuthConfig
- type ExtensionSessionInfoMemo
- type ExtensionSessionView
- type ExtensionStackMetadata
- type ExtensionToolLister
- type ExtensionWarning
- type ExternalEditorFailure
- type FetchUpdateManifestOptions
- type FileEntry
- type FindInitialModelOptions
- type FirstTimeSetupComponent
- type FirstTimeSetupOptions
- type FirstTimeSetupResult
- type FirstTimeSetupSettings
- type FooterComponent
- func (s *FooterComponent) GetWorkingMessage() string
- func (s *FooterComponent) GitBranch() string
- func (s *FooterComponent) ProviderCount() int
- func (s *FooterComponent) Render(width int) []string
- func (s *FooterComponent) ResetContextUsage()
- func (s *FooterComponent) SetAgentName(name string)
- func (s *FooterComponent) SetAutoCompactEnabled(enabled bool)
- func (s *FooterComponent) SetContextUsage(tokens *int, contextWindow int)
- func (s *FooterComponent) SetCwd(cwd string)
- func (s *FooterComponent) SetExtensionStatus(key, text string)
- func (s *FooterComponent) SetModel(m *ai.Model)
- func (s *FooterComponent) SetName(name string)
- func (s *FooterComponent) SetProviderCount(n int)
- func (s *FooterComponent) SetSession(session FooterSession)
- func (s *FooterComponent) SetSubscriptionResolver(resolve func(*ai.Model) bool)
- func (s *FooterComponent) SetSuppressedByExtFooter(v bool)
- func (s *FooterComponent) SetThinkingLevel(level string)
- func (s *FooterComponent) SetTurnContextUsage(u *ai.Usage)
- func (s *FooterComponent) SetUsingSubscription(v bool)
- func (s *FooterComponent) SetWorking(b bool)
- func (s *FooterComponent) SetWorkingMessage(message string)
- type FooterDataProvider
- func (d *FooterDataProvider) Dispose()
- func (d *FooterDataProvider) GetAvailableProviderCount() int
- func (d *FooterDataProvider) GetExtensionStatuses() map[string]string
- func (d *FooterDataProvider) GetGitBranch() string
- func (d *FooterDataProvider) ObserveChange(observe func()) func()
- func (d *FooterDataProvider) OnBranchChange(fn func()) func()
- func (d *FooterDataProvider) SetCwd(cwd string)
- func (d *FooterDataProvider) SetExtensionStatus(key, text string)
- func (d *FooterDataProvider) SetProviderCount(n int)
- type FooterSession
- type FullscreenExitOutput
- type GraphArgs
- func (a GraphArgs) Bool(i int) (bool, error)
- func (a GraphArgs) Has(i int) bool
- func (a GraphArgs) Int(i int) (int, error)
- func (a GraphArgs) OptString(i int) (*string, error)
- func (a GraphArgs) Raw(i int) json.RawMessage
- func (a GraphArgs) String(i int) (string, error)
- func (a GraphArgs) Unmarshal(i int, decode func(json.RawMessage) error) error
- type GraphProjectTrustStore
- type GraphSessionManager
- type GraphSettingsManager
- type HandleReads
- type HelpCommandInfo
- type HostActionBinder
- type InitialModelResult
- type InitialModelRuntime
- type InteractiveForkResult
- type InteractiveMode
- func (m *InteractiveMode) ClearEditor()
- func (m *InteractiveMode) Init(ctx context.Context) (err error)
- func (m *InteractiveMode) RoutedModelSelection() *RoutedModelSelection
- func (m *InteractiveMode) Run(ctx context.Context) (err error)
- func (m *InteractiveMode) SessionManager() *Session
- func (m *InteractiveMode) ShowPackageUpdateNotification(packages []string)
- func (m *InteractiveMode) ShutdownFromSignal()
- func (m *InteractiveMode) Stop(fullscreenExitOutput ...FullscreenExitOutput) error
- type InteractiveModeOptions
- type InteractiveReplacement
- type InteractiveRuntime
- type InteractiveSessionHandle
- type InteractiveThemeController
- type InteractiveThemeControllerOptions
- type InteractiveTuiOptions
- type KeyID
- type KeybindingConflict
- type KeybindingDefinition
- type KeybindingValue
- type KeybindingsManager
- func (km *KeybindingsManager) ExtensionKeybindingTable() map[string]any
- func (km *KeybindingsManager) GetConflicts() []KeybindingConflict
- func (km *KeybindingsManager) GetDefinition(action string) (KeybindingDefinition, bool)
- func (km *KeybindingsManager) GetEffectiveConfig() map[string]KeybindingValue
- func (km *KeybindingsManager) GetKeys(action string) []KeyID
- func (km *KeybindingsManager) GetResolvedBindings() map[string][]string
- func (km *KeybindingsManager) GetUserBindings() map[string][]KeyID
- func (km *KeybindingsManager) KeyText(action string) string
- func (km *KeybindingsManager) KeybindingIDs() []string
- func (km *KeybindingsManager) Matches(input, action string) bool
- func (km *KeybindingsManager) MatchesEditorHistory(input string) bool
- func (km *KeybindingsManager) MatchesSelectPage(input string) bool
- func (km *KeybindingsManager) Reload()
- func (km *KeybindingsManager) Resolve(input string) string
- func (km *KeybindingsManager) Save(path string) error
- func (km *KeybindingsManager) SetUserBindings(bindings map[string][]KeyID)
- type LabelEntry
- type LatestPiRelease
- type LoadPromptTemplatesOptions
- type LoadPromptTemplatesResult
- type LoadSkillsFromDirOptions
- type LoadSkillsOptions
- type LoadSkillsResult
- type LoginHeaderOptions
- type MarkdownSettings
- type MermaidRenderingMode
- type MessageEntry
- type MissingSessionCwdError
- type ModelChangeEntry
- type ModelCycleResult
- type ModelDataSource
- type ModelEntry
- type ModelMutationOptions
- type ModelOperationBindings
- type ModelOperationBridge
- type ModelPriceSource
- type ModelReferenceRequest
- type ModelReferenceResult
- type ModelReferenceStatus
- type ModelReferenceTarget
- type ModelRegistry
- func (r *ModelRegistry) AvailabilityReadContext(ctx context.Context) context.Context
- func (r *ModelRegistry) AvailableProviderCount() int
- func (r *ModelRegistry) AwaitModelTasks(ctx context.Context, tasks ...func(context.Context) error) error
- func (r *ModelRegistry) BugReportProviderInfo(providerID string) *BugReportProvider
- func (r *ModelRegistry) CacheReadPrice(providerID, modelID string) float64
- func (r *ModelRegistry) CheckRegistryAuth(ctx context.Context, id string) (*ai.AuthCheck, error)
- func (r *ModelRegistry) CloseModelTasks()
- func (r *ModelRegistry) CompatibilityRequestHeaders(model *ai.Model) (ai.ProviderHeaders, bool, error)
- func (r *ModelRegistry) ConfiguredRequestAuthStatus(providerID string) (ai.AuthStatus, bool)
- func (r *ModelRegistry) ExtensionProviderAuth(ctx context.Context, providerID string) (*ai.AuthResult, error)
- func (r *ModelRegistry) ExtensionProviderAuthStatus(providerID string) ai.AuthStatus
- func (r *ModelRegistry) ExtensionRefresh(ctx context.Context, allowNetwork *bool, providers []string, force *bool) CatalogRefreshResult
- func (r *ModelRegistry) GetAll() []ModelEntry
- func (r *ModelRegistry) GetAllModelData() []*ai.Model
- func (r *ModelRegistry) GetAllModelDataSources() []ModelDataSource
- func (r *ModelRegistry) GetAllProviderModelData() []ai.AnyModel
- func (r *ModelRegistry) GetAvailable() []ModelEntry
- func (r *ModelRegistry) GetAvailableAllModelDataContext(ctx context.Context, providerID string) ([]ai.AnyModel, error)
- func (r *ModelRegistry) GetAvailableModelData() []*ai.Model
- func (r *ModelRegistry) GetAvailableModelDataContext(ctx context.Context, providerID string) ([]*ai.Model, error)
- func (r *ModelRegistry) GetCompatibilityRequestConfig(model *ai.Model) (CompatibilityRequestConfig, error)
- func (r *ModelRegistry) GetNativeModels(id ...string) []*ai.Model
- func (r *ModelRegistry) GetProvider(id string) *ai.ModelsProvider
- func (r *ModelRegistry) GetProviderAllModelData(id string) []ai.AnyModel
- func (r *ModelRegistry) GetProviderAuth(ctx context.Context, id string) (*ai.AuthResult, error)
- func (r *ModelRegistry) GetProviderAuthChecks(ctx context.Context) (map[string]*ai.AuthCheck, error)
- func (r *ModelRegistry) GetProviderAuthStatus(providerID string) ai.AuthStatus
- func (r *ModelRegistry) GetProviderDisplayName(providerID string) string
- func (r *ModelRegistry) GetProviderModelData(id string) []*ai.Model
- func (r *ModelRegistry) GetProviderModelDataByID(id, modelID string) *ai.Model
- func (r *ModelRegistry) GetRegisteredNativeProvider(id string) *ai.ModelsProvider
- func (r *ModelRegistry) GetRegisteredProviderConfig(id string) *ProviderConfigInput
- func (r *ModelRegistry) GetRegisteredProviderIDs() []string
- func (r *ModelRegistry) GetTypedProvider(id string, fallback ai.ModelsStreamFunction) *ai.ModelsProvider
- func (r *ModelRegistry) GetTypedProviders(fallback func(id string) ai.ModelsStreamFunction) []*ai.ModelsProvider
- 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) HasRegisteredProvider(providerID string) bool
- func (r *ModelRegistry) HoldRegistrationRefresh() (release func())
- func (r *ModelRegistry) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
- func (r *ModelRegistry) LoadError() string
- func (r *ModelRegistry) LoginNativeProvider(ctx context.Context, id string, kind ai.AuthType, ...) (ai.Credential, error)
- func (r *ModelRegistry) LogoutNativeProvider(ctx context.Context, id string) error
- func (r *ModelRegistry) ModelProviderIDs() []string
- func (r *ModelRegistry) ModelTaskContext(ctx context.Context) context.Context
- func (r *ModelRegistry) NativeModels() *ai.Models
- func (r *ModelRegistry) NativeProvider(id string) *extension.NativeProvider
- func (r *ModelRegistry) NativeProviderAuth(ctx context.Context, id string, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
- func (r *ModelRegistry) ObserveChanges(notify func()) func()
- func (r *ModelRegistry) ProviderInsecure(providerID string) bool
- func (r *ModelRegistry) ProviderIsSubscription(providerID string) bool
- func (r *ModelRegistry) ProviderStreamSimple(name string, api ai.API) extension.ProviderStreamSimple
- 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) ReadCredential(ctx context.Context, providerID string) (*ai.Credential, error)
- func (r *ModelRegistry) Refresh()
- func (r *ModelRegistry) RefreshCatalogs(ctx context.Context, options CatalogRefreshOptions) CatalogRefreshResult
- func (r *ModelRegistry) RefreshModelRuntime(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (r *ModelRegistry) RefreshNativeProviders(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (r *ModelRegistry) RegisterExtensionProvider(name string, configMap extension.ProviderConfig) error
- func (r *ModelRegistry) RegisterNativeModelsProvider(provider *ai.ModelsProvider) error
- func (r *ModelRegistry) RegisterNativeProvider(ctx context.Context, p *extension.NativeProvider) error
- func (r *ModelRegistry) RegisterProviderInput(id string, input ProviderConfigInput, fallback ai.ModelsStreamFunction) error
- func (r *ModelRegistry) RemoveRuntimeAPIKey(providerID string)
- func (r *ModelRegistry) RemoveRuntimeAPIKeyOperation(ctx context.Context, providerID string) error
- func (r *ModelRegistry) RequestAuthHeaders(model *ai.Model, headers ai.ProviderHeaders) ai.ProviderHeaders
- func (r *ModelRegistry) Resolve(providerID, modelID string) (ModelEntry, bool)
- func (r *ModelRegistry) ResolveCompatibilityModelAuth(ctx context.Context, model *ai.Model) (*ai.AuthResult, error)
- func (r *ModelRegistry) ResolveGeneratedModel(providerID, modelID string, generated *ai.GeneratedModel) ModelEntry
- func (r *ModelRegistry) ResolveRegistryModelAuth(ctx context.Context, model *ai.Model, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
- func (r *ModelRegistry) ResolveRegistryProviderAuth(ctx context.Context, id string, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
- func (r *ModelRegistry) ResolveRegistryTypedModelAuth(ctx context.Context, model ai.AnyModel, ...) (*ai.AuthResult, error)
- func (r *ModelRegistry) RuntimeAPIKey(providerID string) (string, bool)
- func (r *ModelRegistry) RuntimeModels() []RuntimeModel
- func (r *ModelRegistry) SetAPIStream(fn func(id string) ai.ModelsStreamFunction)
- func (r *ModelRegistry) SetAuthStorage(auth *ai.AuthStorage)
- func (r *ModelRegistry) SetAvailabilityRefresh(refresh func(context.Context, []string) ai.ModelsRefreshResult)
- func (r *ModelRegistry) SetAvailabilitySnapshot(configured func(providerID string) bool, ...)
- func (r *ModelRegistry) SetCatalogBaseURL(baseURL string)
- func (r *ModelRegistry) SetChangeListener(notify func()) func()
- func (r *ModelRegistry) SetCredentialStore(store ai.CredentialStore)
- 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) SetRuntimeAPIKeyOperation(ctx context.Context, providerID, apiKey string) error
- func (r *ModelRegistry) StartModelTask(ctx context.Context, work func(context.Context)) bool
- func (r *ModelRegistry) StartRegistrationRefresh(ctx context.Context)
- func (r *ModelRegistry) UnregisterProvider(name string)
- func (r *ModelRegistry) YieldToRegistrationRefresh(ctx context.Context)
- type ModelResolverRuntime
- type ModelScopeDiagnostic
- type ModelScopeRuntime
- type NavigateTreeOptions
- type NavigateTreeResult
- type NewSessionOptions
- type OutputPad
- type PackageManagerOwner
- type PackageSource
- type ParsedSkillBlockFromText
- type PathMetadata
- type PersonalizeCatalog
- type PiSourceInfo
- type ProcessFileOptions
- type ProcessedCLIArgs
- type ProgramStatusReporter
- type ProjectTrustDecision
- type ProjectTrustOption
- type ProjectTrustStore
- func (s *ProjectTrustStore) Get(cwd string) (ProjectTrustDecision, error)
- func (s *ProjectTrustStore) GetEntry(cwd string) (entry *ProjectTrustStoreEntry, err error)
- func (s *ProjectTrustStore) Set(cwd string, decision ProjectTrustDecision) error
- func (s *ProjectTrustStore) SetMany(updates []ProjectTrustUpdate) error
- type ProjectTrustStoreEntry
- type ProjectTrustUpdate
- type ProjectedSessionEntry
- type PromptTemplate
- type ProviderConfigInput
- type ProviderRetryConfig
- type ProviderRetrySettings
- type QuietStartup
- type RawEntry
- 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)
- func (r *RequestAuthRuntime) SynchronizeCredentialState(ctx context.Context, providerID string, ...) error
- type RequestAuthRuntimeOptions
- type ResolveCliModelResult
- type ResolveModelScopeResult
- type ResolvedPath
- type ResolvedResource
- func AmbientExtensionResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
- func AmbientPromptResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
- func AmbientSkillResources(cwd, agentDir string, sm *SettingsManager, project, user bool) []ResolvedResource
- func AmbientSkillResourcesIn(scan *AgentsSkillScan, cwd, agentDir string, sm *SettingsManager, ...) []ResolvedResource
- func AmbientThemeResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
- func OrderResolvedResources(packages, ambient []ResolvedResource) []ResolvedResource
- func SkillEntryResources(resources []ResolvedResource) []ResolvedResource
- type ResourceSourceInfo
- type RetryConfig
- type RetrySettingsJSON
- type RoutedModelSelection
- type RuntimeModel
- type RuntimeProvider
- type ScopedModel
- type SelfUpdateActionResult
- type SelfUpdateCommand
- type SelfUpdatePackageTarget
- type SelfUpdateProvenance
- type SelfUpdateRelease
- type SelfUpdateTier
- type Session
- func (s *Session) Accounting() SessionAccounting
- func (s *Session) AppendBashExecution(message BashExecutionMessage) (string, error)
- func (s *Session) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int, details any, fromHook bool, ...) (string, error)
- func (s *Session) AppendCompactionHookUndefined(summary, firstKeptEntryID string, tokensBefore int, details any, ...) (string, error)
- func (s *Session) AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
- func (s *Session) AppendCustomEntry(customType string, data any) (string, error)
- func (s *Session) AppendCustomMessageEntry(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) (string, error)
- func (s *Session) AppendMessage(message SessionMessage) (string, error)
- func (s *Session) AppendModelChange(provider, modelID string) (string, error)
- func (s *Session) AppendSessionInfo(name string) (string, error)
- func (s *Session) AppendSessionInfoName(name string) (id, current string, err error)
- func (s *Session) AppendThinkingLevelChange(level string) (string, error)
- func (s *Session) AppendUsage(kind, provider, model string, usage ai.Usage, note string) (UsageEntry, error)
- func (s *Session) Branch(forkFromID string) error
- func (s *Session) BranchWithSummary(parentID *string, summary string, details any, fromHook bool, usage *ai.Usage) (string, error)
- func (s *Session) BuildContext(leafID *string) []agent.AgentMessage
- func (s *Session) BuildContextEntries() []SessionEntry
- func (s *Session) BuildSessionContext() SessionContext
- func (s *Session) BuildSessionProjection() SessionProjection
- func (s *Session) BuildSessionProjectionCalls() int64
- func (s *Session) BuildSessionProjectionView() SessionProjection
- func (s *Session) CWD() string
- func (s *Session) CheckSavedForFork() error
- func (s *Session) CountEntriesOfType(entryType string) int
- func (s *Session) CreateBranchedSession(leafID string) (string, error)
- func (s *Session) EntryReads() int64
- func (s *Session) ExportHeader() SessionHeader
- func (s *Session) FooterUsageTotals() footerUsageTotals
- func (s *Session) GetBranch(fromID ...string) []SessionEntry
- func (s *Session) GetBranchSystemMessages() []agent.AgentMessage
- func (s *Session) GetChildren(parentID string) []SessionEntry
- func (s *Session) GetContextBranch() []SessionEntry
- func (s *Session) GetCwd() string
- func (s *Session) GetEntries() []SessionEntry
- func (s *Session) GetEntry(id string) (SessionEntry, bool)
- func (s *Session) GetEntryCount() int
- func (s *Session) GetHeader() SessionHeader
- func (s *Session) GetLabel(id string) (string, bool)
- func (s *Session) GetLeafEntry() (SessionEntry, bool)
- func (s *Session) GetLeafID() *string
- func (s *Session) GetMessageEntriesWithRole(role string) []SessionEntry
- func (s *Session) GetSessionDir() string
- func (s *Session) GetSessionFile() *string
- func (s *Session) GetSessionId() string
- func (s *Session) GetSessionName() string
- func (s *Session) GetTree() []*SessionTreeNode
- func (s *Session) ID() string
- func (s *Session) IsPersisted() bool
- func (s *Session) KeptRangeOnBranch() bool
- func (s *Session) NewSession(options *NewSessionOptions) (string, error)
- func (s *Session) ParentSession() string
- func (s *Session) Path() string
- func (s *Session) Persist(entry SessionEntry) error
- func (s *Session) RawEntriesPage(cursor, maxBytes int) (page []json.RawMessage, next, total int)
- func (s *Session) ResetLeaf()
- func (s *Session) Revision() uint64
- func (s *Session) SetCacheReadPriceSource(prices ModelPriceSource)
- func (s *Session) SetLeafID(id *string) error
- func (s *Session) SetPath(p string)
- func (s *Session) SetSessionFile(path string) error
- func (s *Session) UndecodableCount() int
- func (s *Session) UsesDefaultSessionDir() bool
- type SessionAccounting
- type SessionCacheWaste
- type SessionContext
- type SessionContextModel
- type SessionCwdIssue
- type SessionEntry
- type SessionEntryBase
- type SessionHeader
- type SessionHeaderScanLimitError
- type SessionImportFileNotFoundError
- type SessionInfo
- type SessionInfoEntry
- type SessionList
- type SessionListOptions
- type SessionListProgress
- 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, idOption ...string) (*Session, error)
- func (sm *SessionManager) ForkToNewSession(source *Session, userMsgEntryID string) (*Session, string, error)
- func (sm *SessionManager) ListAllSessions(options ...SessionListOptions) ([]SessionInfo, error)
- func (sm *SessionManager) ListCurrentSessions(options ...SessionListOptions) ([]SessionInfo, error)
- func (sm *SessionManager) ListSessions(options ...SessionListOptions) ([]SessionInfo, error)
- func (sm *SessionManager) Load(path string) (*Session, error)
- func (sm *SessionManager) Open(path string, cwdOverride ...string) (*Session, error)
- func (sm *SessionManager) RenameSession(path, newName string) error
- func (sm *SessionManager) SessionDir() string
- type SessionMessage
- type SessionProjection
- type SessionSelectorComponent
- func (s *SessionSelectorComponent) Cancelled() bool
- func (s *SessionSelectorComponent) CapturesViewportInput() bool
- func (s *SessionSelectorComponent) Done() bool
- func (s *SessionSelectorComponent) Focused() bool
- func (s *SessionSelectorComponent) GetSessionList() *SessionList
- func (s *SessionSelectorComponent) HandleInput(data string)
- func (s *SessionSelectorComponent) IsDirty() bool
- func (s *SessionSelectorComponent) NativeNode() (frontend.Node, bool)
- func (s *SessionSelectorComponent) SelectedPath() string
- func (s *SessionSelectorComponent) SetFocused(focused bool)
- type SessionSelectorOptions
- type SessionShareDestination
- type SessionTokenStats
- type SessionTreeNode
- type SessionUsageBreakdown
- type SessionsLoader
- 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) GetDefaultTools() []string
- func (s Settings) GetEditorPaddingX() int
- func (s Settings) GetHideThinkingBlock() bool
- func (s Settings) GetImageAutoResize() bool
- func (s Settings) GetImageWidthCells() int
- func (s Settings) GetMaskSecretInput() bool
- func (s Settings) GetOutputPad() OutputPad
- func (s Settings) GetQuietStartup() QuietStartup
- 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 SettingsCallbacks
- type SettingsConfig
- type SettingsError
- type SettingsManager
- func NewInMemorySettingsManager(settings Settings) *SettingsManager
- func NewSettingsManager(cwd, agentDir string) *SettingsManager
- func NewSettingsManagerFromStorage(storage SettingsStorage, options SettingsManagerCreateOptions) *SettingsManager
- func NewSettingsManagerWithOptions(cwd, agentDir string, options SettingsManagerCreateOptions) *SettingsManager
- func NewSettingsManagerWithProjectTrust(cwd, agentDir string, projectTrusted bool) *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) ExtensionSettings() extension.Settings
- func (sm *SettingsManager) ExtensionSettingsJSON() json.RawMessage
- func (sm *SettingsManager) Flush() error
- func (sm *SettingsManager) Get() Settings
- func (sm *SettingsManager) GetAllModelThinkingLevels() map[string]ai.ThinkingLevel
- 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(model ...*ai.Model) (int, error)
- func (sm *SettingsManager) GetCompactionReserveTokens(model ...*ai.Model) (int, error)
- func (sm *SettingsManager) GetCompactionSettings(model ...*ai.Model) (CompactionConfig, error)
- func (sm *SettingsManager) GetDefaultModel() string
- func (sm *SettingsManager) GetDefaultProjectTrust() DefaultProjectTrust
- func (sm *SettingsManager) GetDefaultProvider() string
- func (sm *SettingsManager) GetDefaultThinkingLevel() ai.ThinkingLevel
- 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) GetExtensionChangelogVersion(key string) (string, bool)
- func (sm *SettingsManager) GetExtensionPaths() []string
- func (sm *SettingsManager) GetExtensionsAutoUpgrade() bool
- func (sm *SettingsManager) GetExtensionsTypescriptRuntime() string
- func (sm *SettingsManager) GetExternalEditorCommand() string
- func (sm *SettingsManager) GetFollowUpMode() string
- func (sm *SettingsManager) GetFullscreenCopyOnSelect() bool
- func (sm *SettingsManager) GetFullscreenExitOutput() FullscreenExitOutput
- func (sm *SettingsManager) GetFullscreenScrollbar() string
- func (sm *SettingsManager) GetFullscreenWheelScrollLines() WheelScrollLines
- 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() MermaidRenderingMode
- func (sm *SettingsManager) GetModelThinkingLevel(provider, modelID string) ai.ThinkingLevel
- func (sm *SettingsManager) GetNpmCommand() []string
- func (sm *SettingsManager) GetOrCreateDeviceID() string
- func (sm *SettingsManager) GetOutputPad() OutputPad
- 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() QuietStartup
- func (sm *SettingsManager) GetRetryEnabled() bool
- func (sm *SettingsManager) GetRetrySettings() RetryConfig
- func (sm *SettingsManager) GetSessionDir() (string, error)
- func (sm *SettingsManager) GetSessionShareDestination() SessionShareDestination
- func (sm *SettingsManager) GetSettings() Settings
- 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) GetThemeSetting() *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() tui.TuiMode
- func (sm *SettingsManager) GetWarnings() WarningSettings
- func (sm *SettingsManager) GetWebSocketConnectTimeoutMs() (*int, error)
- 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) ObserveChange(observe func()) func()
- func (sm *SettingsManager) Reload()
- func (sm *SettingsManager) RemoveModelThinkingLevel(provider, modelID string) error
- func (sm *SettingsManager) ResolvedDefaultTools() []string
- 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) SetDefaultProjectTrust(trust DefaultProjectTrust) error
- func (sm *SettingsManager) SetDefaultProvider(p string) error
- func (sm *SettingsManager) SetDefaultThinkingLevel(level ai.ThinkingLevel) 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) SetExtensionChangelogVersion(key, version 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 FullscreenExitOutput) error
- func (sm *SettingsManager) SetFullscreenScrollbar(mode string) error
- func (sm *SettingsManager) SetFullscreenWheelScrollLines(lines WheelScrollLines) 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) SetMaskSecretInput(enabled bool) error
- func (sm *SettingsManager) SetMermaidRenderingMode(mode MermaidRenderingMode) error
- func (sm *SettingsManager) SetModelThinkingLevel(provider, modelID string, level ai.ThinkingLevel) error
- func (sm *SettingsManager) SetNpmCommand(cmd []string) error
- func (sm *SettingsManager) SetOutputPad(padding OutputPad) 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 QuietStartup) error
- func (sm *SettingsManager) SetRetryEnabled(enabled bool) error
- func (sm *SettingsManager) SetSessionShareDestination(destination SessionShareDestination) 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 tui.TuiMode) 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 SettingsManagerCreateOptions
- type SettingsSelectorComponent
- func (s *SettingsSelectorComponent) GetSettingsList() *tui.SettingsList
- func (s *SettingsSelectorComponent) IsDirty() bool
- func (s *SettingsSelectorComponent) NativeNode() (frontend.Node, bool)
- func (s *SettingsSelectorComponent) NeedsRedraw() bool
- func (s *SettingsSelectorComponent) SurfaceLive() bool
- type SettingsStorage
- type ShareState
- type ShareTool
- type SkillDef
- func DeduplicateSkills(defs []*SkillDef) []*SkillDef
- func DeduplicateSkillsWithDiagnostics(defs []*SkillDef) ([]*SkillDef, []extension.ResourceDiagnostic)
- func LoadSkill(skillsDir, name string) (*SkillDef, error)
- func LoadSkillPath(path string) (*SkillDef, error)
- func LoadSkillsFromPath(path string) ([]*SkillDef, error)
- type SkillFrontmatter
- type SlashCommand
- type SlashCommandCatalog
- func (c SlashCommandCatalog) Commands() []SlashCommandInfo
- func (c SlashCommandCatalog) SourceInfoForPath(path, kind string) PiSourceInfo
- func (c SlashCommandCatalog) SubprocessCommands() []subprocess.CommandInfo
- func (c SlashCommandCatalog) WithPromptSources(templates []PromptTemplate) []PromptTemplate
- func (c SlashCommandCatalog) WithSkillCommandSources(skills []*SkillDef) []*SkillDef
- func (c SlashCommandCatalog) WithSkillSources(skills []*SkillDef) []*SkillDef
- type SlashCommandInfo
- type SlashCommandSource
- type SlashContext
- type SlashHandler
- type SlashMatch
- type SlashRegistry
- func (r *SlashRegistry) All() []HelpCommandInfo
- func (r *SlashRegistry) Dispatch(sc *SlashContext, line string, extCtx *ExtensionContext) error
- func (r *SlashRegistry) DispatchHeadless(sc *SlashContext, line string, extCtx *ExtensionContext) error
- func (r *SlashRegistry) IsBuiltin(name string) bool
- func (r *SlashRegistry) Match(line string) (SlashMatch, bool)
- 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 StdinBuffer
- type StdinBufferOptions
- type SteppedSubmenu
- type SteppedSubmenuOptions
- type SteppedSubmenuStep
- type SubprocessHost
- type SubprocessUIBridge
- type SyntheticSourceInfoOptions
- 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 ThemeFile
- type ThinkingBudgetsSettings
- type ThinkingLevelEntry
- type ThinkingSelectorComponent
- func (s *ThinkingSelectorComponent) Focused() bool
- func (s *ThinkingSelectorComponent) GetSelectList() *tui.SelectList
- func (s *ThinkingSelectorComponent) HandleInput(data string)
- func (s *ThinkingSelectorComponent) NativeNode() (frontend.Node, bool)
- func (s *ThinkingSelectorComponent) SetFocused(focused bool)
- type ThinkingSuffixMode
- type TierError
- type ToolCallEventResult
- type ToolConflict
- type ToolRendererCard
- type ToolRenderers
- type TrailingEntries
- type TrustSelection
- type TrustSelectorComponent
- type TrustSelectorOptions
- type UpdateBinary
- type UpdateManifest
- type UsageEntry
- type WarningSettings
- type WheelScrollLines
Constants ¶
const ( CacheWarmingActionWarm = extension.CacheWarmingActionWarm CacheWarmingActionStop = extension.CacheWarmingActionStop )
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" // EventProviderStreamEvent fires for a parsed provider stream event before normalization (types.ts ProviderStreamEvent). EventProviderStreamEvent = "provider_stream_event" // 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" // MCP servers registered by extensions (types.ts McpServersChangeEvent). EventMcpServersChange = "mcp_servers_change" )
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, independent of the selected configuration directories.
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 BuiltinPathPrefix = "builtin:"
BuiltinPathPrefix is the prefix of built-in tool and extension paths, such as `builtin:read` or `builtin:mcp`. Ports .upstream/v0.99.1/packages/coding-agent/src/core/source-info.ts:14-15.
const CLISourceName = "cli"
CLISourceName is upstream's source for a resource named on the command line (-e, --skill): resource-loader.ts records {source: "cli", scope: "temporary", origin: "top-level"} for it.
const CONFIG_DIR_NAME = "." + AppName
CONFIG_DIR_NAME is the default per-project config directory name.
const CurrentSessionVersion = sessionentry.CurrentSessionVersion
CurrentSessionVersion mirrors upstream `CURRENT_SESSION_VERSION = 3`. Pi schema migrations are applied by session_restore.go.
const DefaultCatalogBaseURL = "https://pi-in-go.dev"
DefaultCatalogBaseURL is the catalog endpoint of the built-in providers. pig divergence (D64): PiG reads the remote catalog overlay from its own pi-in-go.dev instead of Pi's https://pi.dev (remote-catalog-provider.ts:DEFAULT_CATALOG_BASE_URL). An endpoint that does not serve the catalog (404 or 501) leaves the bundled catalog.
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 LlamaExtensionPath = BuiltinPathPrefix + "llama.cpp"
LlamaExtensionPath is the source path upstream gives the built-in llama.cpp extension (`builtin:${name}`). Ports .upstream/v0.99.1/packages/coding-agent/src/extensions/index.ts:8 and core/resource-loader.ts:706-735.
const PackageName = "@pi-in-go/pig"
PackageName is PiG's npm package: the launcher that a global npm-family install owns and that the signed update manifest names. Mirrors upstream PACKAGE_NAME export. automation/release/pig_package.py reads this line, so keep the declaration on one line.
const RadiusProviderID = ai.RadiusProviderID
RadiusProviderID is the built-in Radius provider ID.
const RemoteCatalogRefreshInterval = 4 * time.Hour
RemoteCatalogRefreshInterval is how long a checked catalog stays fresh (remote-catalog-provider.ts:REMOTE_CATALOG_REFRESH_INTERVAL_MS).
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 CodemodeRenderers = ToolRenderers{RenderCall: codemodeRenderCall, RenderResult: codemodeRenderResult}
CodemodeRenderers draw the codemode tool's card: the call shows the script; the result lists the nested calls with their status and the cost of its model calls, followed by the script output without the "Script completed" header, and the time the script has been running (`Elapsed`) or took (`Took`), like bash rows. The codemode tool definition carries them, as upstream's definition spreads codemodeRenderers; they are not built-in renderers keyed by tool name (upstream createAllToolRenderers has no codemode entry).
Ports packages/coding-agent/src/extensions/codemode/renderer.ts (codemodeRenderers).
var DefaultModelPerProviderOrder = []struct{ Provider, ModelID string }{
{"amazon-bedrock", "us.anthropic.claude-opus-4-6-v1"},
{"ant-ling", "Ring-2.6-1T"},
{"anthropic", "claude-opus-4-8"},
{"openai", "gpt-6.1-sol"},
{"azure", "gpt-5.4"},
{"openai-codex", "gpt-6.1-sol"},
{"radius", "balanced"},
{"nvidia", "nvidia/nemotron-3.5-super-vl-120b-a12b"},
{"deepseek", "deepseek-v4-pro"},
{"google", "gemini-3.1-pro-preview"},
{"google-vertex", "gemini-3.1-pro-preview"},
{"github-copilot", "gpt-6.1-sol"},
{"openrouter", "moonshotai/kimi-k2.6"},
{"vercel-ai-gateway", "zai/glm-5.1"},
{"xai", "grok-4.7"},
{"groq", "openai/gpt-oss-120b"},
{"cerebras", "gpt-oss-120b"},
{"zai", "glm-5.3"},
{"zai-coding-cn", "glm-5.3"},
{"mistral", "devstral-medium-latest"},
{"minimax", "MiniMax-M2.7"},
{"minimax-cn", "MiniMax-M2.7"},
{"moonshotai", "kimi-k2.6"},
{"moonshotai-cn", "kimi-k2.6"},
{"huggingface", "moonshotai/Kimi-K2.6"},
{"fireworks", "accounts/fireworks/models/kimi-k3"},
{"together", "moonshotai/Kimi-K3"},
{"baseten", "zai-org/GLM-5.2"},
{"opencode", "kimi-k2.6"},
{"opencode-go", "kimi-k3"},
{"kimi-coding", "kimi-for-coding"},
{"meta", "muse-spark-1.3"},
{"cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.6"},
{"cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.6"},
{"qwen-token-plan", "qwen3.7-max"},
{"qwen-token-plan-cn", "qwen3.7-max"},
{"qwen-token-plan-individual", "qwen3.8-max"},
{"xiaomi", "mimo-v2.6-pro"},
{"xiaomi-token-plan-cn", "mimo-v2.6-pro"},
{"xiaomi-token-plan-ams", "mimo-v2.6-pro"},
{"xiaomi-token-plan-sgp", "mimo-v2.6-pro"},
}
DefaultModelPerProviderOrder preserves the declaration order used by findInitialModel.
var DefaultUpdateTrustRoot string
DefaultUpdateTrustRoot is an optional build-time Ed25519 public key in PEM form, or the same PEM base64-encoded on one line (a multi-line value cannot be passed through -ldflags -X). Distributor installers can instead seed the 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. PiG's own release builds (release-candidate.yml) point it at the latest release's signed update.json; development, go install, and Piglet builds leave it empty.
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 RadiusMcpURL = ai.NormalizeRadiusGatewayURL(ai.DefaultRadiusGateway) + "/mcp"
RadiusMcpURL is the MCP endpoint of the gateway the built-in Radius provider signs in to (core/radius.ts:6).
var RemoteCatalogModelTypes = []ai.ModelType{ai.ModelTypeChat, ai.ModelTypeImage, ai.ModelTypeClassifier}
RemoteCatalogModelTypes are the model types this client can consume. They are sent as `?types=` so the catalog server returns the full-type shard instead of the chat-only one served to clients that predate model types. A server that ignores the parameter still returns the chat-only shard, which this client handles unchanged. upstream: remote-catalog-provider.ts:14-19 (REMOTE_CATALOG_MODEL_TYPES)
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 ActiveExtensionTheme ¶
ActiveExtensionTheme is the active theme as extensions see it (ctx.ui.theme): upstream hands every mode's UI context the global theme.
func ActiveExtensionThemeWire ¶
ActiveExtensionThemeWire is the active theme as the host encodes it for a subprocess extension. The palette is shared between calls while none of its inputs changes, so the caller must not modify it; use ActiveExtensionTheme for a palette an extension handler receives.
func AgentDir ¶
func AgentDir() string
AgentDir returns the writable agent directory. Shared mode uses Pi's environment override; otherwise it uses PiG's. Both expand a leading tilde. It panics with a configroot.UnresolvedError when the home directory is needed and unavailable; ResolveAgentDir reports that as an error.
func AgentDirConfigured ¶
func AgentDirConfigured() bool
AgentDirConfigured reports whether the agent directory comes from its environment variable rather than the default.
func AgentEventContext ¶
func AgentEventContext(ev agent.AgentEvent) context.Context
AgentEventContext returns the context an extension handler for ev runs under. It carries the event's stream scope, so a handler that waits for its extension process releases the stream's continuation queue instead of freezing the provider, as Pi's awaited handler does (agent-session.ts:894-919; runner.ts:emit).
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 AgentStateSystemPrompt ¶
func AgentStateSystemPrompt(messages []agent.AgentMessage) string
AgentStateSystemPrompt returns upstream agent.state.systemPrompt: the prompt replayed from the transcript's system messages (agent.ts:89-91). It excludes a request-only forced prompt and base-prompt changes not yet sent to the model, which AgentSession.systemPrompt includes.
func AmbientPromptPaths ¶
func AmbientPromptPaths(cwd, agentDir string, sm *SettingsManager, project bool) []string
AmbientPromptPaths lists the paths of AmbientPromptResources.
func AmbientSkillPaths ¶
func AmbientSkillPaths(cwd, agentDir string, sm *SettingsManager, project, user bool) []string
AmbientSkillPaths lists the enabled skills that settings and auto-discovery yield once DefaultPackageManager.resolve has keyed each by its SKILL.md and reduced the first-wins accumulator, so an explicit exclusion disables an auto-discovered skill at the same path; a skill that Pi keys by its SKILL.md is listed by its directory (package-manager.ts:365-400, 927-961, 2555-2565).
func AmbientSkillPathsIn ¶
func AmbientSkillPathsIn(scan *AgentsSkillScan, cwd, agentDir string, sm *SettingsManager, project, user bool) []string
AmbientSkillPathsIn is AmbientSkillPaths with the ancestor .agents/skills directories of scan, which must be of cwd.
func ApplyToolModifiers ¶
ApplyToolModifiers applies the `+name` and `-name` entries of entries to base in order: `+name` adds a tool and `-name` removes one. Other entries are ignored. Mirrors upstream applyToolModifiers (settings-manager.ts:236-248).
func AreExperimentalFeaturesEnabled ¶
func AreExperimentalFeaturesEnabled() bool
AreExperimentalFeaturesEnabled reports whether experimental features are on.
func AssertSessionCwdExists ¶
func AuthResultJSON ¶
func AuthResultJSON(result *ai.AuthResult) map[string]any
AuthResultJSON is upstream's AuthResult object: auth with apiKey, headers and baseUrl when set, then env and source.
func AuthenticatedProviders ¶
AuthenticatedProviders returns the subset of ReachableProviders for which credentials are detectable in the environment / auth.json / model registry, without probing the network.
- every other provider: ModelRegistry.HasConfiguredAuth (models.json, then Pi's checkProviderAuth over the stored auth.json credential and the environment)
- 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)
- amazon-bedrock, google-vertex, cloudflare-*: their resolvers' env signals (Pi reads no shared AWS config file)
agentDir is the pig config dir (typically ~/.pig/agent). auth.json and models.json are read from there.
func BeforeExit ¶
func BeforeExit()
BeforeExit is called by a path that is about to end the process with os.Exit and did not claim the record through RecordEnding, or that lost the claim. It never returns while an emergency exit is running, because that exit ends the process with 129 as Pi's does (step 3 of the contract); otherwise it returns once the line another path claimed is on disk. With no ending in flight it returns at once.
func BeginSessionMarker ¶
func BeginSessionMarker(agentDir, version, cwd string)
BeginSessionMarker creates this process's marker file in the agent directory and has the Go runtime copy any unrecovered panic or fatal error into it, in addition to stderr. A clean end removes the file (EndSessionMarker). A file left behind therefore means the process ended some other way, and ReconcileSessionMarkers reports it at the next start. It is best effort: an unwritable agent directory loses the trace, not the session.
func BindAppendEntryAction ¶
func BindAppendEntryAction(bridge HostActionBinder, current func() (*Session, error), appended func(entry CustomEntry, direct *subprocess.DirectEntryAppend) error)
BindAppendEntryAction binds the host's appendEntry action, which every mode serves: upstream's pi.appendEntry and ctx.sessionManager.appendCustomEntry both write the session's log (agent-session.ts _bindExtensionCore). current names the Session to append to, or the error that rejects the action before one exists. appended, when set, runs after a successful append for the mode's own effect (RPC's entry_appended event, the interactive transcript) and gets the direct append request, which only ctx.sessionManager.appendCustomEntry carries.
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 nonempty path to its absolute canonical filesystem form, following symlinks and drive junctions while preserving Windows volume mount points as directories. It preserves the raw input if resolution fails, including an empty or missing path. Mirrors upstream canonicalizePath.
func CatalogRoot ¶
CatalogRoot returns the managed catalog materialization root.
func ChalkApply ¶
ChalkApply is chalk 6.0.0 applyStyle for one style with a color level above zero: an empty string stays empty, an existing close code inside the text is followed by the open code again, and each line break is wrapped in close and open codes (a preceding carriage return stays before the break).
func ChalkColorLevel ¶
func ChalkColorLevel(args []string, getenv func(string) string, lookup func(string) (string, bool), streamIsTTY bool) int
ChalkColorLevel is chalkColorLevel for this platform: chalk's supports-color level for a stream given the arguments and the environment that getenv and lookup read.
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 ComparePackageVersions ¶
ComparePackageVersions compares two release versions the way node-semver's valid()+compare() do: both sides are trimmed and parsed as semantic versions, a single leading "v" is accepted, and build metadata is ignored. It returns -1, 0 or 1 and true, or false when either side is not a semantic version.
Ports packages/coding-agent/src/utils/version-check.ts (comparePackageVersions).
func ConfigDirName ¶
func ConfigDirName() string
ConfigDirName returns the selected per-project configuration directory name.
func ConfigRoot ¶
func ConfigRoot() string
ConfigRoot returns the pig configuration root directory (internal/configroot, the one resolver the host and every extension SDK share).
Resolution order:
- $PIG_HOME if set and non-empty
- $XDG_CONFIG_HOME/pig if XDG_CONFIG_HOME is set and non-empty
- ~/.pig (default)
A leading ~ expands to the home directory. PiG-owned state stays here even when the agent and project directories are shared with Pi. It panics with a configroot.UnresolvedError when the home directory is needed and unavailable.
func ConfiguredSelfUpdateArgv ¶
ConfiguredSelfUpdateArgv is the self-update command the user configured: PI_SELF_UPDATE_COMMAND (whitespace-separated argv, no quoting), else the global selfUpdateCommand setting. It overrides installation-tier detection. pig divergence (D39): PIG_SELF_UPDATE_COMMAND, PiG's product-neutral alias, is read first, as PIG_PACKAGE_DIR precedes PI_PACKAGE_DIR; the user's explicit command is the one owner of the update, selected before any tier.
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 ContextFilesWithheldMessage ¶
ContextFilesWithheldMessage says which project context files an untrusted project did not load, and how to load them. pig additive (D211).
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 CopyToClipboard ¶
CopyToClipboard writes text to the system clipboard, for components outside this package such as the MCP sign-in screen.
func CrashLogPath ¶
CrashLogPath returns the crash log location for an agent directory.
func CrashOutputDir ¶
CrashOutputDir returns the directory that holds one marker file per running interactive session.
func CreateAllToolRenderers ¶
func CreateAllToolRenderers() map[string]ToolRenderers
CreateAllToolRenderers returns the shared built-in render functions, keyed by tool name. Each card supplies its own state and owns its background work.
func CreateInteractiveTui ¶
func CreateInteractiveTui(options InteractiveTuiOptions) tui.TUI
CreateInteractiveTui creates a regular or fullscreen renderer with the shared theme, clipboard and hyperlink behavior. It does not start terminal input or activate a Session.
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 is Pi's getAgentDir (config.ts): the directory named by the agent directory variable (PIG_CODING_AGENT_DIR, or PI_CODING_AGENT_DIR when PIG_USE_PI_DIRS=1) with a leading tilde expanded, else Pi's ~/.pi/agent in shared mode, else <ConfigRoot>/agent. It panics with a configroot.UnresolvedError when the home directory is needed and unavailable; ResolveDefaultAgentDir reports that as an error.
func DefaultModelPerProvider ¶
DefaultModelPerProvider returns the defaults shared by startup and authentication.
func DefaultSkillsDir ¶
func DefaultSkillsDir() string
DefaultSkillsDir returns the user agent's skills directory.
func DefaultToolNames ¶
func DefaultToolNames() []string
DefaultToolNames returns the tools enabled at startup when `defaultTools` does not change them.
func DiscoverAncestorAgentsSkillDirs ¶
DiscoverAncestorAgentsSkillDirs walks from startDir up to the git root (or filesystem root), collecting .agents/skills directories at each level (package-manager.ts collectAncestorAgentsSkillDirs).
func DiscoverPromptFile ¶
DiscoverPromptFile returns the SYSTEM.md or APPEND_SYSTEM.md file a loader reads: the workspace file when project resources are trusted, otherwise the agent directory file, or "" when neither exists (resource-loader.ts discoverSystemPromptFile, discoverAppendSystemPromptFile).
func DispatchAgentLoopEvent ¶
func DispatchAgentLoopEvent(runner *inproc.Runner, ev agent.AgentEvent, currentMessage *extension.AgentMessage)
DispatchAgentLoopEvent maps one agent-loop event to the extension runner. Session awaits extension dispatch before notifying public listeners, as agent-session.ts::_handleAgentEvent does. Each message_update carries its own shallow message and full provider event; currentMessage retains the message_start value for callers that track it.
func EarlyModelStream ¶
func EarlyModelStream(transport ai.Transport) func(context.Context, map[string]any, map[string]any) (*ai.AssistantMessageEventStream, error)
EarlyModelStream is the model stream for the pi-ai functions (`completeSimple`, `streamSimple`) an extension calls while its module loads. Pi runs them in its own process with no registration gate and no Session: the model is the caller's own object and the request goes through the global API providers.
func EndSessionMarker ¶
func EndSessionMarker()
EndSessionMarker removes this process's marker file after an exit that already left its own trace or was requested.
func EnsureSessionDir ¶
EnsureSessionDir creates a persisted session's directory as Pi's SessionManager constructor does: it skips any path that exists, even a file, and otherwise creates it recursively with Node's error text (session-manager.ts:1011-1013: existsSync, then mkdirSync).
func ExitLogPath ¶
ExitLogPath returns the log of unexpected exits for an agent directory.
func ExpandPromptTemplate ¶
func ExpandPromptTemplate(line string, templates []PromptTemplate) (string, bool)
ExpandPromptTemplate consumes a /name command separated from its arguments by ECMAScript whitespace. A matching template returns its expanded body and true; a non-command or unknown name returns an empty string and false. Upstream: packages/coding-agent/src/core/prompt-templates.ts:318-334.
func ExpandSkillCommand ¶
ExpandSkillCommand reads the selected skill at invocation time, strips frontmatter, and appends trimmed arguments. Unknown skills are not expanded. Read and parse errors leave input unchanged and carry a skill_expansion diagnostic. Ports packages/coding-agent/src/core/agent-session.ts (_expandSkillCommand).
func ExpandTildePath ¶
ExpandTildePath normalizes a filesystem path as upstream expandTildePath does. Mirrors upstream config.ts expandTildePath, which is normalizePath: a leading ~ expands and a file:// URL becomes its path. Pi throws for an invalid URL, which a string result cannot do, so the path then keeps its tilde-expanded text.
func ExportFileToHTML ¶
ExportFileToHTML is the CLI's --export: exportFromFile (core/export-html/index.ts) opens the session file as SessionManager.open does, so a missing file, a directory, a file that is not a session and an empty file (which becomes a new session) answer as Pi's, then writes the HTML. The input and the output path are resolved and normalized like Pi's resolvePath and normalizePath; an empty outputPath becomes <app>-session-<input basename>.html in the working directory.
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 ExportSessionToHTML ¶
func ExportSessionToHTML(sessionFile, outputPath string, getToolRenderers func(name string) *extension.ToolRenderers, cwd string, state ShareState, themeName string) (string, error)
ExportSessionToHTML writes the session file as HTML the way upstream exportSessionToHtml does and returns the path written. An in-memory session (empty sessionFile) and a session whose file is not written yet fail with upstream's messages. outputPath is normalized as upstream normalizePath does and written relative to the process working directory without creating its parent; an empty outputPath becomes pig-session-<session basename>.html. themeName is the export theme ExportThemeName chose (empty exports with the active theme). state is the live agent state upstream passes to exportSessionToHtml: the export embeds its system prompt and active tool schemas. A Piglet that strips export-html gets the stripped error before any of these checks.
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 ExportThemeName ¶
ExportThemeName is the theme AgentSession.exportToHtml exports with (agent-session.ts exportToHtml): the first candidate (the caller's themeName option, then the settings theme) that names a registered theme, or empty when none does.
func ExportToolRenderers ¶
func ExportToolRenderers(runner *inproc.Runner) func(name string) *extension.ToolRenderers
ExportToolRenderers is upstream AgentSession's getToolRenderers for HTML exports: the resolvers of runner's extensions in load order, then the tools they registered. A nil runner draws no tool through renderers. upstream: packages/coding-agent/src/core/agent-session.ts:exportToHtml (getToolRenderers)
func ExtensionEntryIdentity ¶
func ExtensionEntryIdentity(sess *Session, direct *subprocess.DirectEntryAppend) (string, string, error)
ExtensionEntryIdentity returns the id and timestamp of a custom entry an extension appends: those ctx.sessionManager.appendCustomEntry already generated in the extension process and returned, or new ones for pi.appendEntry. Upstream generates the id in the log's own process, checked against every existing id, so an id the log already holds is refused.
func ExtensionForImageMIME ¶
ExtensionForImageMIME returns the canonical file extension for a supported image MIME, or "" if unknown. Matches upstream's extensionForImageMimeType.
func ExtensionModelRegistryState ¶
func ExtensionModelRegistryState(registry *ModelRegistry, catalog []*ai.Model) map[string]any
ExtensionModelRegistryState returns the registry snapshot for extension processes: the catalog under "models", each provider's display name, base URL, auth status, configured auth and OAuth use under "providers", and the registry error under "error". Upstream ModelRuntime keeps the same facts in its snapshot (all models, configured providers, auth checks) and answers getAll, getAvailable, hasConfiguredAuth, getProviderAuthStatus, getProvider, getProviderDisplayName, isUsingOAuth and getError from them.
func ExtensionPackageRoot ¶
ExtensionPackageRoot is the directory of the Package that supplied an extension, or "" for a top-level extension and for a local source that is a single script file (crash-log.ts singleFilePackage, which mirrors package-manager.ts leaving packageRoot unset for a file).
func ExtensionSessionDir ¶
ExtensionSessionDir is the session directory a mode passes for its sessions: the --session-dir or configured directory as upstream SessionManager keeps it (utils/paths.ts normalizePath: a leading ~ and a file:// URL expand, any other path stays as given), or empty for the default.
func ExtensionSessionInfo ¶
func ExtensionSessionInfo(view ExtensionSessionView) map[string]any
ExtensionSessionInfo is the header part of ReadonlySessionManager the Node runtime replicates with each state push.
func ExtensionSessionRead ¶
func ExtensionSessionRead(view ExtensionSessionView, method string, args json.RawMessage) (any, error)
ExtensionSessionRead answers one ReadonlySessionManager read by its upstream method name. A result of nil is upstream's undefined or null.
func ExtensionThemePalette ¶
ExtensionThemePalette is the palette extensions receive for theme (ctx.ui.theme): its resolved escape sequences, and the host-resolved appearance and concrete colors.
func ExtensionToolInfos ¶
func ExtensionToolInfos(runner ExtensionToolLister, allowed, excluded map[string]struct{}) []subprocess.ToolInfo
ExtensionToolInfos mirrors upstream AgentSession.getAllTools (agent-session.ts): the session's tool definition registry, not its active tools. Every built-in tool the --tools allowlist and --exclude-tools denylist admit is listed, active or not, in createAllToolDefinitions order; extension tools follow in registration order, first registration winning across extensions, and an extension tool named like a built-in takes that built-in's place (_refreshToolRegistry). --no-builtin-tools only changes the active set, so it lists the built-ins too.
allowed is nil when no allowlist is in force; an empty allowlist admits nothing, as --no-tools does.
func ExtensionToolInfosScoped ¶
func ExtensionToolInfosScoped(runner ExtensionToolLister, allowed, excluded map[string]struct{}, scope *extension.ToolScope) []subprocess.ToolInfo
ExtensionToolInfosScoped is ExtensionToolInfos with the consumer's registry predicate (pig additive, D23): a tool the scope rejects is unregistered, so it is not listed. A nil scope lists exactly what ExtensionToolInfos lists.
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 ExtensionsInLoadOrderWithExplicit ¶
func ExtensionsInLoadOrderWithExplicit(configured, builtins []extension.Extension, explicit []string) []extension.Extension
ExtensionsInLoadOrderWithExplicit is ExtensionsInLoadOrder with the built-ins named by `-e builtin:<name>` (explicit holds their paths) placed after the extensions of the other -e sources and ahead of the settings extensions. resource-loader.ts:566-575 lists the -e paths before the settings paths and package-manager.ts resolveExtensionSources sorts them by resourcePrecedenceRank, which puts a built-in after every file or package extension (:192-198); loadFinalExtensionSet orders the extensions by that list (:765-775). The other built-ins and the inline factories follow the configured extensions. The -e extensions are the configured ones whose source is the CLI.
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 wraps the released entries for a plain Markdown output sink. The interactive command uses separate border, title and padded Markdown components.
func FormatCrashExtensionHint ¶
FormatCrashExtensionHint formats the warning shown for matching extensions.
func FormatMissingSessionCwdError ¶
func FormatMissingSessionCwdError(issue SessionCwdIssue) string
func FormatMissingSessionCwdPrompt ¶
func FormatMissingSessionCwdPrompt(issue SessionCwdIssue) string
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 FormatTokens ¶
FormatTokens is footer.ts formatTokens for presentations outside the interactive footer.
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. The delay is a float64 like the JavaScript number: a lifetime from a models.json promptCache can exceed the int64 range.
func GetCwdRelativePath ¶
GetCwdRelativePath returns the path relative to cwd, with the platform separator as Pi's path.relative gives it, when filePath resolves inside cwd, or "" when it is outside cwd or either path fails to resolve (Pi's resolvePath throws for an invalid file URL). Both paths are normalized as resolvePath does: a leading ~ expands to the home directory and a file URL becomes its path.
func GetDefaultSessionDirPath ¶
GetDefaultSessionDirPath derives storage from the selected agent directory, without consulting another configuration root.
upstream: session-manager.ts getDefaultSessionDirPath (both paths go through resolvePath first, so a trailing or doubled separator, a `..` segment, `~` and a relative cwd name the same directory as their resolved form)
func GetDocsPath ¶
func GetDocsPath() string
GetDocsPath is the directory of this binary's documentation bundle, which the system prompt, the login help and the codemode description point at, or "" when the bundle is not on disk: the binary embeds none, or startup could not write it. upstream: config.ts:449 getDocsPath (join(getPackageDir(), "docs")); pig additive (D22): PiG materializes its documentation bundle under the configuration root, one content-addressed directory per build, instead of shipping it in the package directory.
func GetExamplesPath ¶
func GetExamplesPath() string
GetExamplesPath is where the system prompt says PiG's examples are. upstream: config.ts:454 getExamplesPath (join(getPackageDir(), "examples")); pig additive (D22): PiG's examples are published in its repository, so the location is prompts.PigExamplesLocation, a URL, not a directory.
func GetPackageDir ¶
func GetPackageDir() string
GetPackageDir is upstream getPackageDir (config.ts:393): PIG_PACKAGE_DIR or PI_PACKAGE_DIR when set, normalized as Pi's normalizePath does (a leading ~ expands, a file:// URL becomes its path); otherwise the installation directory of a compiled pig, the directory holding the running executable. 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 returns the model's prompt-cache lifetime for the request's retention. Explicit retention wins over the environment; none or a missing tier has no lifetime.
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 GetReadmePath ¶
func GetReadmePath() string
GetReadmePath is the README of the documentation bundle, the "Main documentation" entry of the system prompt, or "" when the bundle is not on disk. upstream: config.ts:444 getReadmePath (join(getPackageDir(), "README.md")); pig additive (D22): the README is the bundle's own.
func GetToolListError ¶
GetToolListError validates a tool list from `--tools`: it is either an allowlist of plain names and patterns or a list of only `+name` and `-name` entries with exact names. It returns the problem, or "" when the list is valid. Mirrors upstream getToolListError (settings-manager.ts:218-228).
func GitInstallRoot ¶
GitInstallRoot returns the managed Git checkout root for one settings scope.
func GraphAPIModel ¶
func GraphAPIModel(raw json.RawMessage) (*ai.Model, error)
GraphAPIModel decodes a model object an extension passed that its runtime does not list (Pi's stream takes any Model object).
func GraphClassify ¶
func GraphClassify(ctx context.Context, classify func(context.Context, *ai.ClassifierModel, ai.ClassifierContext, ...ai.ModelsClassifierOptions) ai.ClassifierResult, model, request, options json.RawMessage) json.RawMessage
GraphClassify is ModelRuntime.classify for a model object, context and options an extension sent. It never fails: a failure is the classifier result Pi returns.
func GraphGenerateImages ¶
func GraphGenerateImages(ctx context.Context, generate func(context.Context, *ai.ImageModel, ai.ImagesContext, ...ai.ModelsImagesOptions) ai.AssistantImages, model, request, options json.RawMessage) json.RawMessage
GraphGenerateImages is ModelRuntime.generateImages for a model object, context and options an extension sent. It never fails: a failure is the images result Pi returns.
func GraphMessages ¶
func GraphMessages(raw json.RawMessage) ([]ai.Message, error)
GraphMessages decodes the messages of a request an extension sent (a JSON array of Pi's Message objects).
func GraphModelStreamRequest ¶
func GraphModelStreamRequest(ctx context.Context, model *ai.Model, request map[string]any, bridgeRequest extension.ModelStreamRequest) (context.Context, ai.Context, ai.StreamOptions, error)
GraphModelStreamRequest turns an extension's model request (the wire map of a modelStream call) into the provider call's context, transcript and options, as the Session's stream does.
func GraphProjectTrustStoreStatic ¶
func GraphProjectTrustStoreStatic(_ context.Context, method string, raw json.RawMessage) (any, error)
GraphProjectTrustStoreStatic runs the trust-manager.ts functions that are not methods of the class.
func GraphProviderConfig ¶
func GraphProviderConfig(input *ProviderConfigInput) (map[string]any, error)
GraphProviderConfig is the JSON of a registered ProviderConfigInput, as Pi's getRegisteredProviderConfig returns it for a configuration without functions.
func GraphSessionManagerStatic ¶
func GraphSessionManagerStatic(ctx context.Context, scope subprocess.SessionGraphScope, method string, raw json.RawMessage) (any, error)
GraphSessionManagerStatic runs the static function of Pi's SessionManager that constructs no object.
func HasProjectContextFile ¶
HasProjectContextFile reports whether the walk from cwd to the filesystem root finds a project context file: one that LoadProjectContextFilesScoped skips with loadProject false. It reads nothing. pig additive (D211).
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 HiddenToolNames ¶
HiddenToolNames lists the tools whose declarations the loadout hides, sorted (agent-session.ts hiddenTools).
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 InvokeProviderStreamSimple ¶
func InvokeProviderStreamSimple(ctx context.Context, id string, callback extension.ProviderStreamSimple, model *ai.Model, transcript ai.TranscriptContext, options ai.StreamOptions) (stream *ai.AssistantMessageEventStream, err error)
InvokeProviderStreamSimple is the shared dynamic-to-native callback boundary. The caller resolves request credentials before invoking it.
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 IsLocalPath ¶
IsLocalPath reports whether value is a local path rather than a package source, a built-in extension or a remote URL. Bare names, relative paths, and file URLs are local. Ports .upstream/v0.99.1/packages/coding-agent/src/utils/paths.ts:45-64 (a `builtin:` value names a built-in extension).
func IsNewerPackageVersion ¶
IsNewerPackageVersion reports whether candidate is newer than current. When either side is not a semantic version, any difference between the trimmed strings counts as newer.
Ports packages/coding-agent/src/utils/version-check.ts (isNewerPackageVersion).
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 IsSyntheticPath ¶
IsSyntheticPath reports whether path names no file: `builtin:<name>` or an angle-bracket path. Ports .upstream/v0.99.1/packages/coding-agent/src/core/source-info.ts:27-29.
func IsToolModifier ¶
IsToolModifier reports whether a defaultTools entry is a `+name` or `-name` modifier (settings-manager.ts:215-217).
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 KeyIDPattern ¶
func KeyIDPattern() string
KeyIDPattern is the KeyIdSchema pattern source of key-id-schema.ts, with each key escaped as /[\\^$.*+?()[\]{}|]/g does.
func KeybindingsFile ¶
func KeybindingsSchemaArtifact ¶
func KeybindingsSchemaArtifact() configschema.Artifact
KeybindingsSchemaArtifact is the schemas/keybindings.schema.json artifact that configschema.Render takes with its own four.
func LastLeaf ¶
func LastLeaf() *string
LastLeaf is Pi's undefined leafId: the branch ends at the last entry. A nil leafID is Pi's null (the empty branch before the first entry), and a leafID that names no entry also falls back to the last one.
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 LoadExtensionTheme ¶
LoadExtensionTheme is the palette of the theme pi-coding-agent's initTheme(name) installs in an extension's process: the registered theme of that name in the terminal's color mode, or the system theme for an absent name or one no theme has (theme.ts initTheme falls back to it silently).
func MarkPathIgnoredByCloudSync ¶
func MarkPathIgnoredByCloudSync(path string)
MarkPathIgnoredByCloudSync best-effort marks a directory as ignored by cloud sync providers. Mirrors upstream markPathIgnoredByCloudSync.
func MigrateSessionEntries ¶
MigrateSessionEntries applies Pi's v1 tree and v2 custom-message migrations, preserving JSON member order. The version is the first session header's `version`, 1 when the entries have no header or the header omits it (session-manager.ts migrateToCurrentVersion); the entries migrate in place and entries already at the current version stay unchanged.
func MkdirSessionDir ¶
MkdirSessionDir creates a session directory and its missing parents with mode 0700. pig divergence (D132): Pi creates them with the umask default (0755), so every other user of the machine can read the sessions (pi-mono #10770). An existing directory keeps its mode.
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 NewEditorWithOptions ¶
func NewEditorWithOptions(options CustomEditorOptions, editorOptions ...tui.EditorOption) *tui.Editor
NewEditorWithOptions is the editor that `new CustomEditor(tui, theme, keybindings, options)` builds (editor.ts:373-381 and custom-editor.ts:26-30): the options set the padding, the autocomplete row limit and whether status is embedded in the border.
func NewTreeSelectorComponent ¶
func NewTreeSelectorComponent(tree []*SessionTreeNode, currentLeafID *string, terminalHeight int, onSelect func(entryID string), onCancel func(), onLabelChange func(entryID string, label *string), initialSelectedID *string, initialFilterMode string) *tui.TreeSelectorComponent
NewTreeSelectorComponent is Pi's TreeSelectorComponent constructor (tree-selector.ts constructor): it takes the session tree as SessionTreeNode data and reads the tool-call arguments and the current leaf from that tree, as Pi's flattenTree does (tree-selector.ts:202-262). The tui selector is the engine; tui cannot import this package's SessionTreeNode, so the adapter that presents the data as tui.TreeNode rows lives here.
func NormalizeChangelogLinks ¶
NormalizeChangelogLinks is normalizeChangelogLinks(markdown, version): inline Markdown link targets become tag-pinned GitHub source links, and legacy pi-mono repository URLs are canonicalized. version is "x.y.z" or "vx.y.z" (entry.Version()).
func NormalizeExtensionPaths ¶
func NormalizeExtensionPaths(cwd string, paths *extension.ResourcesDiscoverAggregateResult) (*extension.ResourcesDiscoverAggregateResult, error)
NormalizeExtensionPaths resolves extension-discovered file URLs and local paths against the session cwd, without changing the extension attribution. Invalid URLs fail before callers update resource state, with Node's own error as Pi's bindExtensions throws it. Ports packages/coding-agent/src/core/resource-loader.ts
func NormalizePromptContent ¶
func NormalizePromptContent(content []ai.UserContentBlock, autoResize bool, model *ai.Model, processImage imageprocessing.ProcessImageFunc) []ai.UserContentBlock
NormalizePromptContent applies the given 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 OpenBrowser ¶
func OpenBrowser(target string)
OpenBrowser opens target in the platform browser. The launch is best-effort, as upstream's: callers still present the target to the user, so a launcher failure is not reported. Ports packages/coding-agent/src/utils/open-browser.ts
func OpenExternalEditor ¶
func OpenExternalEditor(ctx context.Context, initial string, configuredEditor string) (string, error)
OpenExternalEditor resolves the command with SettingsManager's precedence, writes initial to prompt.md in a private pi-editor-* directory under the system temp directory, runs the editor on that file with inherited stdio, and returns the file contents on success. On editor non-zero exit OR read error, returns initial unchanged plus a non-nil error.
The directory 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 PackageManagerHomeDir ¶
PackageManagerHomeDir is Pi's getHomeDir (package-manager.ts:233-235), `process.env.HOME || homedir()`: a nonempty HOME on every platform, else Node's os.homedir() (the platform home variable, an explicit empty value included, else the user database's home directory). Where Node's call throws, because no home variable is set and the user database has no entry for the process's user, so does this, with *nodehome.Error: Pi's getHomeDir throws there, and a project that supplies a "user" skills directory through a path relative to the working directory must not be the answer. pig divergence (D200): Pi never gets here without a home directory, because it crashes at import in every mode (tools-manager.ts:11 getBinDir -> getAgentDir -> normalizePath -> homedir(), utils/paths.ts:89); PiG, whose PIG_HOME needs no home directory, runs `--version`, `list` and the other commands that load no resources, and fails with Pi's error here, where Pi's home lookup would run.
func ParsePromptArgs ¶
ParsePromptArgs splits arguments using ECMAScript whitespace outside single- and double-quoted runs. Empty quoted strings are omitted, and backslashes are literal. Upstream: packages/coding-agent/src/core/prompt-templates.ts:24-55.
func PigDocsFile ¶
PigDocsFile is the path of name in this binary's documentation bundle. ok is false when the process strips docs or the bundle is not on disk (the binary embeds none, or startup could not write it): no text may point at a file that is not there. pig additive (D92): Stock PiG strips nothing. pig additive (D22): a bundle that is not on disk is not named.
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 PngTranscoder ¶
PngTranscoder is upstream loadPngTranscoder's transcoder: base64 image data to oriented base64 PNG data, or false when the data does not decode.
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 selected workspace-local configuration root.
func ProjectContextEntry ¶
func ProjectContextEntry(entry SessionEntry, messages []agent.AgentMessage, edit *ContextEditEntry) []agent.AgentMessage
ProjectContextEntry applies the latest context edit for one entry (session-manager.ts projectContextEntry). Only user, assistant, tool-result, and custom messages take replacement content; other roles pass through.
func ProjectStateDir ¶
ProjectStateDir returns one additive capability's workspace-scoped state directory.
func ProviderLoginHelp ¶
func ProviderLoginHelp() string
ProviderLoginHelp mirrors upstream auth-guidance.ts. pig additive (D92): a stripped /login or docs bundle leaves its sentence out.
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. A rename that another process's handle blocks is retried until the handle closes, within fsretry.RenameBudget, or until ctx ends.
func RFC3339NowNano ¶
func RFC3339NowNano() string
RFC3339NowNano returns the current UTC time in Pi's millisecond ISO format.
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 ModelRuntime can compose: every provider in the built-in catalog plus ollama, which is configured from the environment rather than declared in the catalog.
coding.BuildModel's buildProviderForEntry switches on a provider's API kind, not its id, so every catalog provider is wireable. Deriving this from the catalog keeps a new upstream provider from being silently omitted from the picker.
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 command backends before the native helper on Linux and the native helper directly elsewhere. Termux reads no image clipboard. Native transfer errors propagate unchanged, and unsupported formats are converted to PNG. The caller owns cancellation and awaits the transfer.
func ReadExitLogTail ¶
ReadExitLogTail returns the newest n lines of the exit log.
func ReadNativeProviderModelData ¶
func ReadNativeProviderModelData(r *ModelRegistry)
ReadNativeProviderModelData reads the catalog of every provider whose models come from provider code, in provider order, and discards the models. A caller that has no use for the composed models but must still run the provider callbacks Pi's getModels runs uses it. The catalogs of the other providers are static data whose read has no effect to observe.
func ReadStoredCredentialEntry ¶
func ReadStoredCredentialEntry(providerID, authPath string) json.RawMessage
ReadStoredCredentialEntry is the one-off read of readStoredCredential (auth-storage.ts:496-506): the entry of providerID in the auth.json at authPath (the agent directory's auth.json when authPath is empty), as written, without instantiating a store or resolving configured key values. A missing or malformed file, an absent entry and a JavaScript-falsy entry (null, false, 0, "") yield nil: a caller that tests `if (credential)` treats them alike.
func ReadStoredCredentialEntryAt ¶
func ReadStoredCredentialEntryAt(providerID, authPath string) json.RawMessage
ReadStoredCredentialEntryAt is ReadStoredCredentialEntry for a path the caller passed explicitly: an empty path is not the default, because the default parameter applies only to an omitted argument, so reading "" fails and yields nil.
func RealPathSync ¶
RealPathSync is Node's fs.realpathSync of path: the absolute path with every symlink and drive junction followed, failing where Node throws. Like CanonicalizePath it keeps the case and 8.3 short names of components that are not links on Windows (filepath.EvalSymlinks would expand them to the stored long form), so a caller that hands the path to another program passes the spelling Pi passes.
func ReconcileSessionMarkers ¶
ReconcileSessionMarkers reports every session whose marker file outlived its process. A marker that another host or PID namespace wrote is left alone: that session may be running. A marker with a Go crash report becomes a crash record, shown at this start and attached by /bug. A marker without one became an exit.log line: the session was killed from outside (SIGKILL, memory pressure, power loss) or died where Go could not write.
func RecordEnding ¶
RecordEnding appends the one exit.log line for the ending that ends this process and reports whether reason is it. A caller that does not own the record blocks until the owner's line is on disk, so returning means the record is complete either way and the caller may exit.
func RecordExit ¶
func RecordExit(agentDir, reason string)
RecordExit appends one line saying why this process is ending without a user request. It is best effort: the caller is already exiting, and a failed write must not change how it exits.
func RecoverUncaught ¶
func RecoverUncaught()
RecoverUncaught is deferred first in a goroutine that nothing awaits. Without a handler it panics again, so the Go runtime reports the original panic as it does for an unguarded goroutine.
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 RemoteMouseEvent ¶
func RemoteMouseEvent(event tui.TuiMouseEvent) extension.RemoteMouseEvent
RemoteMouseEvent is event as it crosses to an extension: every field of pi-tui's TuiMouseEvent, the modifiers and wheel delta included. The overlay and editor mouse paths use it, and the extension conformance rows hand their events through it.
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. Like upstream main.ts reportDiagnostics, which styles them with the default chalk instance, the colors follow chalk's stdout color level, not whether stderr is a terminal.
func ResolveAgentDir ¶
ResolveAgentDir is AgentDir with an error, never a relative path, when the home directory is needed and unavailable.
func ResolveDefaultAgentDir ¶
ResolveDefaultAgentDir is DefaultAgentDir with an error, never a relative path, when the home directory is needed and unavailable.
func ResolvePath ¶
ResolvePath normalizes input and baseDir, then resolves the input to an absolute path. An empty baseDir uses the process working directory. Invalid file URLs return an error. Ports packages/coding-agent/src/utils/paths.ts:102-106.
func ResolvePromptInput ¶
ResolvePromptInput returns the BOM-stripped contents of the file input names, or input itself when no such file exists or it cannot be read (resource-loader.ts resolvePromptInput).
func ResourcePathKey ¶
ResourcePathKey is Pi's getResourcePathKey, the key that deduplicates resource paths: a synthetic path (`builtin:<name>`, `<inline:...>`) as it is, because it names no file and its lookup is case-sensitive, and a file path by its real path in the platform's casing (resolvepath.ComparisonKey).
func ResourcePaths ¶
func ResourcePaths(resources []ResolvedResource) []string
ResourcePaths lists the paths of the enabled resources.
func ResourcePrecedenceRank ¶
func ResourcePrecedenceRank(metadata PathMetadata) int
ResourcePrecedenceRank is package-manager.ts resourcePrecedenceRank: project settings entries, project auto-discovered, user settings entries, user auto-discovered, Package resources, then built-in extensions.
func ResourcesDiscoverReason ¶
ResourcesDiscoverReason maps a session_start reason to the resources_discover reason. Pi's AgentSession passes "reload" for a reload and "startup" for every other Session start, including one a replacement created (agent-session.ts:2941; the union is "startup" | "reload", extensions/types.ts:551-555).
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 RunConfiguredSelfUpdateCommand ¶
func RunConfiguredSelfUpdateCommand(ctx context.Context, cmd *SelfUpdateCommand) error
RunConfiguredSelfUpdateCommand runs the user's own update command with the terminal attached. It has no deadline of its own: the command is the user's, as Pi's runSelfUpdate spawns it with inherited stdio and waits.
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 the startup migrations, including the persisted keybinding-name rewrite. Auth writes return errors; malformed or unwritable keybindings are left alone, as in upstream runMigrations.
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/pi-clipboard-<uuid>.<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(SessionListOptions) ([]SessionInfo, error), allLoader func(SessionListOptions) ([]SessionInfo, error), opts StartupUIOptions, ) (path string, selected bool, err error)
SelectStartupSession is Pi's selectSession(currentSessionsLoader, allSessionsLoader, settingsManager) (cli/session-picker.ts:15-54), the --resume picker. Ports packages/coding-agent/src/cli/session-picker.ts. It runs the same session selector used by /resume before cwd-bound runtime services exist. Loaders run off the input owner, receive cancellation and progress options, and settle before teardown returns. Confirmed deletion tries trash before unlink; renaming is unavailable. It returns selected=false when the user cancels, where Pi resolves null.
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. Concurrent replacements of the same executable fail before downloading.
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. Concurrent replacements of the same executable fail before downloading; the installation lock remains held through commit or rollback.
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 SetUncaughtGoroutineHandler ¶
SetUncaughtGoroutineHandler installs the handler that RecoverUncaught calls and returns a function that removes it. The handler owns ending the process. It is also the receiver of Chord's uncaught failures (a replicated-state listener failure no onError handled): state.ts reportErrorAsync rethrows in a microtask, which reaches the same uncaughtException handler, after the reporting call.
func SettingsFileExists ¶
SettingsFileExists reports whether agentDir holds settings.json: Pi's first-time setup test (startup-ui.ts:139).
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 SignalName ¶
SignalName names a termination signal the way a shell does.
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 StreamAPILeaf ¶
func StreamAPILeaf(ctx context.Context, simple bool, model, request map[string]any, transport ai.Transport, callbacks extension.ModelStreamRequest) (*ai.AssistantMessageEventStream, error)
StreamAPILeaf runs one pi-ai builtin API request for a process that has no extension runtime and no Session: model is the pi-ai model the caller passed (provider, id, api, baseUrl, headers, compat), request its context and stream options (the caller supplies the API key or auth headers, as pi-ai's own API functions require). It is the provider bridge subprocess's stream: pi-ai compat stream/streamSimple over the global API registry, with the extension wire's decoding. pig divergence (D74): builtin pi-ai API implementations run in PiG's Go providers; this is the transport for callers outside an extension connection.
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 SyntheticPathSource ¶
SyntheticPathSource is the source of a path that names no file: "builtin" for `builtin:<name>`, or the prefix of an angle-bracket path such as "inline" for `<inline:name>`. It is empty for file paths. Ports .upstream/v0.99.1/packages/coding-agent/src/core/source-info.ts:17-25.
func SystemMessageFromAgentMessage ¶
func SystemMessageFromAgentMessage(message agent.AgentMessage) (ai.SystemMessage, bool)
SystemMessageFromAgentMessage reads a projected system-role message.
func SystemPromptSkills ¶
func SystemPromptSkills(skills []*SkillDef) []extension.SystemPromptSkill
SystemPromptSkills is the Skill shape Pi hands extensions in systemPromptOptions.skills (skills.ts Skill).
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 ToolExecutionResultOf ¶
func ToolExecutionResultOf(result agent.AgentToolResult, elapsed time.Duration) tui.ToolResultUpdate
ToolExecutionResultOf converts an agent tool result to the argument of tui.ToolExecutionComponent.UpdateResult. The agent result itself travels as Value so a definition's result renderer receives the tool's own object.
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 without coalescing text or moving images. An empty array clears the prior content.
func TopLevelResourcePaths ¶
func TopLevelResourcePaths(autoDir string, entries []string, kind packagecontent.Kind) []string
TopLevelResourcePaths lists a scope's settings entries, then its auto-discovered resources, as package-manager.ts resourcePrecedenceRank orders them.
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 UsePiDirs ¶
func UsePiDirs() bool
UsePiDirs reports whether the user explicitly selected Pi's configuration directories.
func ValidateAutoDiscoveredOverrides ¶
func ValidateAutoDiscoveredOverrides(cwd, agentDir string, sm *SettingsManager, projectTrusted bool) error
ValidateAutoDiscoveredOverrides returns the first error Pi's addAutoDiscoveredResources throws: an override pattern of a settings resource array that minimatch cannot compile, met while the auto-discovered resources are checked against it in Pi's order (package-manager.ts:2413-2575). Project extensions, skills, ancestor .agents skills, prompts and themes come first when the project is trusted, then the user ones, ~/.agents skills among them.
func WireEarlyModelStream ¶
func WireEarlyModelStream(bridge ModelOperationBridge, transport ai.Transport)
WireEarlyModelStream installs EarlyModelStream on a bridge. The host has no Session yet, so the Session-owned surface of WireModelOperations replaces it when it is installed.
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 WithPersonalizedCatalog ¶
func WithPersonalizedCatalog(provider *ai.ModelsProvider, personalize PersonalizeCatalog, catalogBaseURL string, localGeneratedAt *float64) *ai.ModelsProvider
WithPersonalizedCatalog is WithRemoteCatalog for a provider whose list depends on the credential: on each network refresh the catalog (the bundled models plus a newer pi.dev catalog) is passed through personalize and the result is saved. The saved entry holds the personalized list, not the pi.dev catalog, and replaces the catalog, including offline. The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an empty catalog saved by an older pi after a failed or missing pi.dev catalog) falls back to the bundled models. upstream: remote-catalog-provider.ts:withPersonalizedCatalog (pi-mono ee409a85)
func WithRemoteCatalog ¶
func WithRemoteCatalog(provider *ai.ModelsProvider, catalogBaseURL string, localGeneratedAt *float64) *ai.ModelsProvider
WithRemoteCatalog adds a persisted catalog overlay to a static built-in provider. localGeneratedAt is the generation time, in Unix milliseconds, of the bundled catalog; nil means a stored catalog is always newer. upstream: remote-catalog-provider.ts:62-168 (withRemoteCatalog)
func WithheldProjectContextFiles ¶
WithheldProjectContextFiles lists the paths of the project context files that LoadProjectContextFilesScoped skips with loadProject false, root-first. pig additive (D211).
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 AgentsSkillDir ¶
AgentsSkillDir is one ancestor .agents/skills directory and the skills discovered in it.
type AgentsSkillScan ¶
type AgentsSkillScan struct {
// contains filtered or unexported fields
}
AgentsSkillScan is one walk of the ancestor .agents/skills directories of cwd (package-manager.ts collectAncestorAgentsSkillDirs, without the user's ~/.agents/skills, :2466-2468) and the skills discovered in each (:2505-2519). Pi's resolve() walks them once; a scan made for one resolve gives every consumer of that resolve, the skills it loads and their source infos, the same walk. It walks on first use.
func NewAgentsSkillScan ¶
func NewAgentsSkillScan(cwd string) *AgentsSkillScan
NewAgentsSkillScan returns the scan of cwd's ancestor .agents/skills directories.
func (*AgentsSkillScan) Dirs ¶
func (s *AgentsSkillScan) Dirs() []AgentsSkillDir
Dirs returns the scanned directories, nearest first.
type AppKeybinding ¶
type AppKeybinding string
AppKeybinding is upstream AppKeybinding (core/keybindings.ts:60), keyof AppKeybindings: the closed set of the coding agent's own keybinding ids.
const ( AppInterrupt AppKeybinding = "app.interrupt" AppClear AppKeybinding = "app.clear" AppExit AppKeybinding = "app.exit" AppSuspend AppKeybinding = "app.suspend" AppThinkingCycle AppKeybinding = "app.thinking.cycle" AppThinkingSave AppKeybinding = "app.thinking.save" AppModelCycleForward AppKeybinding = "app.model.cycleForward" AppModelCycleBackward AppKeybinding = "app.model.cycleBackward" AppModelSelect AppKeybinding = "app.model.select" AppToolsExpand AppKeybinding = "app.tools.expand" AppThinkingToggle AppKeybinding = "app.thinking.toggle" AppSessionToggleNamedFilter AppKeybinding = "app.session.toggleNamedFilter" AppEditorExternal AppKeybinding = "app.editor.external" AppMessageCopy AppKeybinding = "app.message.copy" AppMessageFollowUp AppKeybinding = "app.message.followUp" AppMessageDequeue AppKeybinding = "app.message.dequeue" AppClipboardPasteImage AppKeybinding = "app.clipboard.pasteImage" AppSessionNew AppKeybinding = "app.session.new" AppSessionTree AppKeybinding = "app.session.tree" AppSessionFork AppKeybinding = "app.session.fork" AppSessionResume AppKeybinding = "app.session.resume" AppTreeFoldOrUp AppKeybinding = "app.tree.foldOrUp" AppTreeUnfoldOrDown AppKeybinding = "app.tree.unfoldOrDown" AppTreeEditLabel AppKeybinding = "app.tree.editLabel" AppTreeToggleLabelTimestamp AppKeybinding = "app.tree.toggleLabelTimestamp" AppSessionTogglePath AppKeybinding = "app.session.togglePath" AppSessionToggleSort AppKeybinding = "app.session.toggleSort" AppSessionRename AppKeybinding = "app.session.rename" AppSessionDelete AppKeybinding = "app.session.delete" AppSessionDeleteNoninvasive AppKeybinding = "app.session.deleteNoninvasive" AppModelsSave AppKeybinding = "app.models.save" AppModelsEnableAll AppKeybinding = "app.models.enableAll" AppModelsClearAll AppKeybinding = "app.models.clearAll" AppModelsToggleProvider AppKeybinding = "app.models.toggleProvider" AppModelsReorderUp AppKeybinding = "app.models.reorderUp" AppModelsReorderDown AppKeybinding = "app.models.reorderDown" AppTreeFilterDefault AppKeybinding = "app.tree.filter.default" AppTreeFilterNoTools AppKeybinding = "app.tree.filter.noTools" AppTreeFilterUserOnly AppKeybinding = "app.tree.filter.userOnly" AppTreeFilterLabeledOnly AppKeybinding = "app.tree.filter.labeledOnly" AppTreeFilterAll AppKeybinding = "app.tree.filter.all" AppTreeFilterCycleForward AppKeybinding = "app.tree.filter.cycleForward" AppTreeFilterCycleBackward AppKeybinding = "app.tree.filter.cycleBackward" )
type ArminComponent ¶
type ArminComponent struct {
tui.BaseComponent
// contains filtered or unexported fields
}
func NewArminComponent ¶
func NewArminComponent(ui tui.TUI) *ArminComponent
NewArminComponent is armin.ts's constructor(ui): it picks a random effect, builds the final grid, initializes the effect and starts the animation. Every frame advances the effect on the ui's owner loop (ui.PostToOwner) and calls ui.RequestRender; the animation ends when the effect finishes or the component is disposed.
func (*ArminComponent) Dispose ¶
func (a *ArminComponent) Dispose()
func (*ArminComponent) Invalidate ¶
func (a *ArminComponent) Invalidate()
func (*ArminComponent) Render ¶
func (a *ArminComponent) Render(width int) []string
type BashExecOptions ¶
type BashExecOptions = tools.BashExecOptions
BashExecOptions is a type alias for tools.BashExecOptions.
type BashExecutionEntry ¶
type BashExecutionEntry = sessionentry.BashExecutionEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type BashExecutionMessage ¶
type BashExecutionMessage = sessionentry.BashExecutionMessage
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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 BeforeAgentStartRun ¶
type BeforeAgentStartRun struct {
// Options are the options the handlers shared, or the base options when no handler changed them.
Options extension.BuildSystemPromptOptions
// SelectedTools is an explicit selectedTools edit, which becomes the run's tool loadout. Nil keeps the live active tools, including a handler's setActiveTools call.
SelectedTools []string
// Sections are the run's validated custom prompt sections, or nil.
Sections ai.OrderedSections
// SystemPrompt is the exact replacement a handler returned, or nil.
SystemPrompt *string
// Messages are the custom messages the handlers returned.
Messages []extension.CustomMessageRef
}
BeforeAgentStartRun holds one prompt's per-run inputs after before_agent_start. The Session and interactive mode both derive their run from it.
func ResolveBeforeAgentStartRun ¶
func ResolveBeforeAgentStartRun(base extension.BuildSystemPromptOptions, result *extension.BeforeAgentStartCombinedResult) (BeforeAgentStartRun, error)
ResolveBeforeAgentStartRun applies agent-session.ts:1702-1714 to the options passed to before_agent_start and the combined result, which may be nil. A selectedTools list that differs from the base list is an explicit edit. Invalid section names fail as in system-prompt.ts buildSystemPromptSections; the returned run then carries only SelectedTools, because agent-session.ts:1409-1419 admits the loadout before it builds the sections, so the caller applies it before rejecting the prompt.
func (BeforeAgentStartRun) BaseSections ¶
func (r BeforeAgentStartRun) BaseSections(selectedTools []string, hidden map[string]struct{}) ai.OrderedSections
BaseSections builds the run's structured prompt sections from the run's options, as _preparePromptAndToolLoadout does for every mode (agent-session.ts:1669-1683), before its custom sections apply. selectedTools are the live active tools. The hidden declarations leave the tool list and rules out, so they match the declarations the request carries (agent-session.ts _preparePromptAndToolLoadout).
func (BeforeAgentStartRun) NextTurnOptions ¶
func (r BeforeAgentStartRun) NextTurnOptions(base extension.BuildSystemPromptOptions) extension.BuildSystemPromptOptions
NextTurnOptions refreshes a run's options before a later turn: the live tools, and the base snippets and guidelines under the run's (agent-session.ts:697-706), so a tool registered during the run is listed and an edited entry wins.
func (BeforeAgentStartRun) PromptSections ¶
func (r BeforeAgentStartRun) PromptSections(selectedTools []string, hidden map[string]struct{}) (ai.OrderedSections, error)
PromptSections is BaseSections with the run's validated custom sections applied.
type BinaryUpdate ¶
type BinaryUpdate struct {
LatestPiRelease
CurrentVersion string
Binary UpdateBinary
}
BinaryUpdate is checkForNewPiVersion's newer release plus the current platform's binary that applies it.
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. Any non-empty PI_SKIP_VERSION_CHECK disables this startup check without a request; explicit `pig update` does not call it.
type BlockedStatus ¶
type BlockedStatus struct {
Kind tui.ProgramStatusKind
Message string
}
BlockedStatus is what a dialog waits for: the kind of dialog and the line the terminal shows.
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 BranchSummaryEntry = sessionentry.BranchSummaryEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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
// TakesArguments is true for the commands whose line interactive-mode.ts matches with `text === "/name" || text.startsWith("/name ")`.
// The others match only the exact text, so "/session x" is not /session but a prompt.
TakesArguments bool
// AdditiveArguments accepts argument text Pi's built-in does not take: it reports whether "/name rest" runs the built-in, and headless is true
// for Session.DispatchSlash, which has no picker to open. /reload takes --explain (D21); a headless /fork takes the entry id to fork at.
AdditiveArguments func(rest string, headless bool) bool
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`. pig additive (D92): a command the process strips (pigstrip commands), or whose feature it strips (featureCommands), is not in the list, so no registry, dispatcher or completion derived from it offers the command, and typing it sends it to the model like any unknown slash command.
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(fromID ...string) []SessionEntry
}
CacheWarmerSessionManager is the Session surface the warmer uses. Mirrors Pick<SessionManager, "appendUsage" | "getBranch">.
type CacheWarmingAction ¶
type CacheWarmingAction = extension.CacheWarmingAction
CacheWarmingAction is Pi's warm-or-stop decision, the one type the extension API carries (types.ts CacheWarmingDecisionEvent.action).
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 = extension.CacheWarmingDecisionEvent
CacheWarmingDecisionEvent is fired before each refresh with Pi's decision filled in; an extension may override Action. It is the event the extension API delivers to cache_warming_decision handlers.
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 ¶
type CatalogRefreshResult struct {
Aborted bool
Errors map[string]error
// contains filtered or unexported fields
}
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 entries whose version is newer than sinceVersion. The last-seen version is read as upstream's `lastVersion.split(".").map(Number)` does: each of the first three dot-separated parts is a JavaScript Number, and a part that is missing or not a number counts as 0 (utils/changelog.ts getNewEntries).
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).
func (ChangelogEntry) Version ¶
func (e ChangelogEntry) Version() string
Version is the entry's "major.minor.patch" string (entryVersion).
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 CodemodeMode ¶
type CodemodeMode string
CodemodeMode is how the codemode tool presents tools while it is active. Mirrors upstream CodemodeMode (settings-manager.ts:101).
const ( // CodemodeModeOn appends the codemode declaration to each callable tool's description and lists only tools without direct exposure in the codemode description. CodemodeModeOn CodemodeMode = "on" // CodemodeModeOnly lists every callable tool in the codemode description and does not declare active direct tools to the model. CodemodeModeOnly CodemodeMode = "only" )
type CodemodeSettings ¶
type CodemodeSettings struct {
// Mode defaults to on.
Mode CodemodeMode `json:"mode,omitempty"`
// InlineBudget is the estimated tokens (characters / 4) the codemode description may spend on tool declarations. Default 3000.
InlineBudget *int `json:"inlineBudget,omitempty"`
}
CodemodeSettings mirrors upstream CodemodeSettings (settings-manager.ts:103).
type CommandCatalogVersion ¶
type CommandCatalogVersion struct {
// contains filtered or unexported fields
}
CommandCatalogVersion numbers the states of the command catalog an extension host reads, so the host re-encodes the catalog only when it changed. A state is a published catalog (source, whose identity changes with each publication), the runner that lists the extension commands and the version of those commands; a runner without a version, or a nil source, makes every reading a new state.
func (*CommandCatalogVersion) Version ¶
func (v *CommandCatalogVersion) Version(source any, lister ExtensionCommandLister) uint64
Version returns the number of the catalog's current state. source and lister must be comparable, such as pointers.
type CompactionConfig ¶
CompactionConfig mirrors compaction.CompactionSettings but lives here to avoid an import cycle (compaction imports codingagent for SessionEntry).
type CompactionEntry ¶
type CompactionEntry = sessionentry.CompactionEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func GetLatestCompactionEntry ¶
func GetLatestCompactionEntry(entries []SessionEntry) *CompactionEntry
GetLatestCompactionEntry returns the newest compaction entry, or nil when there is none. As upstream casts the newest entry of that type without validating it, a compaction entry whose JSON does not decode is still the newest: only its base members are set. Mirrors upstream packages/coding-agent/src/core/session-manager.ts getLatestCompactionEntry.
func LatestCompactionEntryOf ¶
func LatestCompactionEntryOf(projection SessionProjection) *CompactionEntry
LatestCompactionEntryOf is GetLatestCompactionEntry of the branch the projection was built from, read from the projection: buildContextEntries puts the newest compaction of the branch first, and a branch without one starts with an entry of another type, so the answer costs one entry and not a walk of the whole branch.
type CompactionModelOverride ¶
type CompactionModelOverride struct {
ReserveTokens *float64 `json:"reserveTokens,omitempty"`
KeepRecentTokens *float64 `json:"keepRecentTokens,omitempty"`
// contains filtered or unexported fields
}
CompactionModelOverride mirrors upstream CompactionModelOverride. Pointers keep an explicit zero, as upstream's `override ?? ordinary` does.
func (CompactionModelOverride) MarshalJSON ¶
func (s CompactionModelOverride) MarshalJSON() ([]byte, error)
func (*CompactionModelOverride) UnmarshalJSON ¶
func (s *CompactionModelOverride) UnmarshalJSON(data []byte) error
type CompactionResult ¶
type CompactionResult struct {
Summary string
FirstKeptEntryID string
TokensBefore int
EstimatedTokensAfter int
Usage *ai.Usage
Details any
}
CompactionResult is the result of manual compaction (agent-session.ts compact()). The public coding package names it coding.CompactionResult.
type CompactionSettingsJSON ¶
type CompactionSettingsJSON struct {
Enabled *bool `json:"enabled,omitempty"`
// ReserveTokens and KeepRecentTokens retain JavaScript numbers until getter validation, including zero, fractions, and non-finite runtime overrides.
ReserveTokens *float64 `json:"reserveTokens,omitempty"`
KeepRecentTokens *float64 `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"`
// contains filtered or unexported fields
}
CompactionSettingsJSON mirrors upstream Settings.compaction JSON shape (settings-manager.ts:74). Pointer to *bool for enabled to distinguish absent vs. explicitly-false.
func (CompactionSettingsJSON) MarshalJSON ¶
func (s CompactionSettingsJSON) MarshalJSON() ([]byte, error)
func (*CompactionSettingsJSON) UnmarshalJSON ¶
func (s *CompactionSettingsJSON) UnmarshalJSON(data []byte) error
type CompatibilityRequestConfig ¶
type CompatibilityRequestConfig struct {
// Headers is nil when neither the model nor the provider configuration defines a header.
Headers ai.ProviderHeaders
// AuthHeader reports that the provider requires a resolved API key in an Authorization header.
AuthHeader bool
}
CompatibilityRequestConfig is the request configuration a model falls back to when its provider auth is unconfigured (provider-composer.ts CompatibilityRequestConfig).
type ContextEditEntry ¶
type ContextEditEntry = sessionentry.ContextEditEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type ContextEditReplacement ¶
type ContextEditReplacement = sessionentry.ContextEditReplacement
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type ContextEditableContent ¶
type ContextEditableContent = sessionentry.ContextEditableContent
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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. Nonempty input paths resolve against the process working directory before discovery.
func LoadProjectContextFilesScoped ¶
func LoadProjectContextFilesScoped(cwd, agentDir string, loadProject bool) []ContextFile
LoadProjectContextFilesScoped is LoadProjectContextFiles for a run that may withhold the project's context files. With loadProject false it loads only the context file in the agent directory and the one in the user's home directory, when that directory is a strict ancestor of cwd. Every other file the walk finds is project context and is skipped without a read. pig additive (D211).
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"`
// contains filtered or unexported fields
}
CrashRecord is one crashes.json entry. Mirrors upstream CrashRecord; Kind is "uncaught_exception" or "fatal_error". A record read from the log keeps the JSON object it came from, so a rewrite and a bug report carry its other members and the types it was written with, as Pi's untyped objects do.
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.
func (CrashRecord) MarshalJSON ¶
func (r CrashRecord) MarshalJSON() ([]byte, error)
MarshalJSON writes the record as the log holds it: the members it was read with, or the fields of a new record.
type CredentialSynchronizationError ¶
type CredentialSynchronizationError struct {
ProviderID string
Operation CredentialSynchronizationOperation
Credential *ai.Credential
Cause error
}
CredentialSynchronizationError reports a committed credential change whose local model/auth snapshot could not be synchronized.
func NewCredentialSynchronizationError ¶
func NewCredentialSynchronizationError(providerID string, operation CredentialSynchronizationOperation, credential *ai.Credential, cause error) *CredentialSynchronizationError
NewCredentialSynchronizationError is `new CredentialSynchronizationError(providerId, operation, credential, { cause })`.
func (*CredentialSynchronizationError) Error ¶
func (e *CredentialSynchronizationError) Error() string
func (*CredentialSynchronizationError) Name ¶
func (*CredentialSynchronizationError) Name() string
Name is the `name` property, "CredentialSynchronizationError".
func (*CredentialSynchronizationError) Unwrap ¶
func (e *CredentialSynchronizationError) Unwrap() error
type CredentialSynchronizationOperation ¶
type CredentialSynchronizationOperation string
CredentialSynchronizationOperation identifies the credential change that committed before synchronization failed.
const ( CredentialSynchronizationLogin CredentialSynchronizationOperation = "login" CredentialSynchronizationLogout CredentialSynchronizationOperation = "logout" CredentialSynchronizationSetRuntimeAPIKey CredentialSynchronizationOperation = "setRuntimeApiKey" CredentialSynchronizationRemoveRuntimeAPIKey CredentialSynchronizationOperation = "removeRuntimeApiKey" )
type CustomEditor ¶
type CustomEditor struct {
*tui.Editor
// OnEscape, OnCtrlD and OnPasteImage replace the handlers registered for app.interrupt, app.exit and app.clipboard.pasteImage while set.
OnEscape func()
OnCtrlD func()
OnPasteImage func()
// OnExtensionShortcut handles extension-registered shortcuts and reports whether it consumed the key.
OnExtensionShortcut func(data string) bool
// contains filtered or unexported fields
}
Ports packages/coding-agent/src/modes/interactive/components/custom-editor.ts
CustomEditor is the default editor with the coding agent's app keybindings (custom-editor.ts CustomEditor extends Editor). Handlers run in the order they were registered, as the Map in upstream iterates; an Editor key none of them takes goes to superInput, which is the editor's own handling.
func NewCustomEditor ¶
func NewCustomEditor(ui tui.TUI, theme tui.EditorTheme, keybindings *KeybindingsManager, options CustomEditorOptions) *CustomEditor
NewCustomEditor is upstream's `new CustomEditor(tui, theme, keybindings, options)`: a default editor built with options and theme, with the app keybindings, whose own input handling (upstream's super.handleInput) takes the keys no app action does. Go's Editor takes no TUI: it renders through the component tree, so the TUI argument is the one the editor is mounted in and is not read. upstream: custom-editor.ts:24-27 constructor(tui, theme, keybindings, options?)
func (*CustomEditor) ActionHandler ¶
func (e *CustomEditor) ActionHandler(action AppKeybinding) (func(), bool)
ActionHandler returns the handler registered for an app action.
func (*CustomEditor) HandleInput ¶
func (e *CustomEditor) HandleInput(data string)
HandleInput is custom-editor.ts handleInput: extension shortcuts first, then the clipboard image paste, interrupt, exit, the explicit editor history bindings, every other app action in registration order, and finally the editor itself.
func (*CustomEditor) OnAction ¶
func (e *CustomEditor) OnAction(action AppKeybinding, handler func())
OnAction registers a handler for an app action (custom-editor.ts onAction); registering an action again replaces its handler and keeps its place.
type CustomEditorOptions ¶
type CustomEditorOptions struct {
// PaddingX is the editor's horizontal padding; omitted is 0 and a negative value is 0.
PaddingX *int
// AutocompleteMaxVisible is the most autocomplete rows shown; omitted is 5, and the value is kept within 3 to 20.
AutocompleteMaxVisible *int
// EmbedWorkingStatus renders working, compaction, summarization and retry status in the editor's top border; omitted is false.
EmbedWorkingStatus bool
// UI is the TUI the editor owns (editor.ts constructor's tui); nil builds the host-driven editor.
UI tui.TUI
}
CustomEditorOptions is custom-editor.ts:5-8 CustomEditorOptions = EditorOptions & { embedWorkingStatus?: boolean }. A nil field is an omitted option.
type CustomEntry ¶
type CustomEntry = sessionentry.CustomEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func AppendExtensionEntry ¶
func AppendExtensionEntry(sess *Session, customType string, data any, direct *subprocess.DirectEntryAppend) (CustomEntry, error)
AppendExtensionEntry validates or allocates the identity and appends under one Session mutation lock. A rejected direct identity cannot overwrite an existing entry.
type CustomEntryComponent ¶
CustomEntryComponent renders a custom session entry through an extension's entry renderer. The host owns transcript spacing; the renderer output is preceded by one Spacer(1). A renderer that panics is replaced by an error box (custom-entry.ts:46-52).
func NewCustomEntryComponent ¶
func NewCustomEntryComponent(entry CustomEntry, renderer extension.EntryRenderer, outputPad int) *CustomEntryComponent
NewCustomEntryComponent builds the component and renders the entry once (custom-entry.ts:18 constructor(entry, renderer, outputPad = 1)); outputPad is the horizontal padding of the renderer-failed box.
func (*CustomEntryComponent) HasContent ¶
func (c *CustomEntryComponent) HasContent() bool
HasContent reports whether the renderer produced a component.
func (*CustomEntryComponent) Invalidate ¶
func (c *CustomEntryComponent) Invalidate()
Invalidate re-renders the entry so theme changes reach the renderer's output.
func (*CustomEntryComponent) IsDirty ¶
func (c *CustomEntryComponent) IsDirty() bool
IsDirty reports a renderer component whose output changed on its own (an extension renderer proxy whose lines arrive after the first frame), so the parent container that caches this component re-renders it.
func (*CustomEntryComponent) SetExpanded ¶
func (c *CustomEntryComponent) SetExpanded(expanded bool)
SetExpanded re-renders the entry with the new expansion state when it changed.
func (*CustomEntryComponent) SetOutputPad ¶
func (c *CustomEntryComponent) SetOutputPad(outputPad int)
SetOutputPad is Pi's setOutputPad(outputPad) (custom-entry.ts:37): the padding changes and the entry is rendered again.
func (*CustomEntryComponent) SurfaceLive ¶
func (c *CustomEntryComponent) SurfaceLive() bool
pig additive (D91): SurfaceLive reports a renderer component that changes on its own, which IsDirty reads, so a TuiSurface rebuilds the entry every frame.
type CustomMessageEntry ¶
type CustomMessageEntry = sessionentry.CustomMessageEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type DefaultProjectTrust ¶
type DefaultProjectTrust string
DefaultProjectTrust is the fallback project-trust mode: upstream `"ask" | "always" | "never"` (settings-manager.ts:110).
const ( DefaultProjectTrustAsk DefaultProjectTrust = "ask" DefaultProjectTrustAlways DefaultProjectTrust = "always" DefaultProjectTrustNever DefaultProjectTrust = "never" )
The DefaultProjectTrust values.
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) error
func (*ExtUIContext) AddAutocompleteProviderWithLifetime ¶
func (u *ExtUIContext) AddAutocompleteProviderWithLifetime(lifetime context.Context, factory extension.AutocompleteProviderFactory) error
AddAutocompleteProviderWithLifetime drops registrations when their owning extension connection ends.
func (*ExtUIContext) AutocompleteProvider ¶
func (u *ExtUIContext) AutocompleteProvider(ctx context.Context) (*extension.AutocompleteProvider, error)
AutocompleteProvider captures the active chain for a subprocess editor. Both editors use that same provider instance.
func (*ExtUIContext) Bell ¶
func (u *ExtUIContext) Bell()
Bell rings the terminal bell between frames (extension.TerminalBeller).
func (*ExtUIContext) ClearHiddenThinkingLabel ¶
func (u *ExtUIContext) ClearHiddenThinkingLabel()
ClearHiddenThinkingLabel is Pi's setHiddenThinkingLabel() with no argument: it restores the default label (extension.HiddenThinkingLabelClearer).
func (*ExtUIContext) ClearWorkingMessage ¶
func (u *ExtUIContext) ClearWorkingMessage()
ClearWorkingMessage is Pi's setWorkingMessage() with no argument: it restores the default working label (extension.WorkingMessageClearer).
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) Custom ¶
func (u *ExtUIContext) Custom(ctx context.Context, factory extension.CustomFactory, opts *extension.CustomOptions) (any, error)
Custom runs an in-process factory and shows its component in the editor slot, or over the screen, until the factory's done callback ends the call with a result. upstream: packages/coding-agent/src/modes/interactive/interactive-mode.ts:2863-2935 (showExtensionCustom)
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() extension.EditorFactory
GetEditorComponent is the factory the last SetEditorComponent installed (interactive-mode.ts:2664 `this.editorComponentFactory`).
func (*ExtUIContext) GetEditorText ¶
func (u *ExtUIContext) GetEditorText() string
GetEditorText reads owner-published expanded text after binding, including paste contents. Before binding the caller owns the editor directly.
func (*ExtUIContext) GetTheme ¶
func (u *ExtUIContext) GetTheme(name string) (extension.Theme, error)
GetTheme loads a theme's portable palette without selecting it. Missing names return absence, as Pi's getThemeByName does. The theme is in the terminal's color mode, as Pi's createTheme defaults it (theme.ts:599-600).
func (*ExtUIContext) GetToolsExpanded ¶
func (u *ExtUIContext) GetToolsExpanded() bool
func (*ExtUIContext) HideTopOverlay ¶
func (u *ExtUIContext) HideTopOverlay(ctx context.Context) (any, error)
HideTopOverlay is Pi's TUI.hideOverlay (tui.ts:829-841) for a subprocess factory's tui: it pops the topmost overlay.
func (*ExtUIContext) Input ¶
func (u *ExtUIContext) Input(ctx context.Context, title, placeholder string, opts 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. A positive opts timeout counts down in the title and cancels the input when it expires.
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) RegisterSprite ¶
func (u *ExtUIContext) RegisterSprite(owner string, definition extension.ValidatedSpriteDefinition) error
RegisterSprite adds an extension's sprite to /sprite (D2). The header redraws, since it may be the saved sprite, drawn as the default until now.
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 mounts remote custom UI as an overlay or editor-slot replacement and waits for its result. The owner loop mounts the component and transfers renderer focus; this caller drains its modal input lease off-loop while the component has focus. Normal completion restores the editor slot and focus before returning.
func (*ExtUIContext) Select ¶
func (u *ExtUIContext) Select(ctx context.Context, title string, options []string, opts 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). A positive opts timeout counts down in the title and cancels the selector when it expires.
func (*ExtUIContext) SetEditorComponent ¶
func (u *ExtUIContext) SetEditorComponent(factory extension.EditorFactory)
SetEditorComponent installs the component factory builds in place of the editor, or with nil restores the editor (interactive-mode.ts setCustomEditorComponent). The factory is called on the owner loop with the TUI, the editor theme and the keybindings.
func (*ExtUIContext) SetEditorText ¶
func (u *ExtUIContext) SetEditorText(text string)
func (*ExtUIContext) SetFooter ¶
func (u *ExtUIContext) SetFooter(factory extension.FooterFactory)
func (*ExtUIContext) SetHeader ¶
func (u *ExtUIContext) SetHeader(factory extension.HeaderFactory)
func (*ExtUIContext) SetHiddenThinkingLabel ¶
func (u *ExtUIContext) SetHiddenThinkingLabel(label string)
func (*ExtUIContext) SetLogin ¶
func (u *ExtUIContext) SetLogin(definition extension.LoginDefinition) error
func (*ExtUIContext) SetRemoteFocus ¶
func (u *ExtUIContext) SetRemoteFocus(ctx context.Context, target extension.RemoteOverlayFocusTarget) (any, error)
SetRemoteFocus is Pi's TUI.setFocus (tui.ts:598-600) for a subprocess factory's tui, with an explicit target.
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(selection extension.ThemeSelection) extension.SetThemeResult
SetTheme disables automatic switching, applies a named theme, and persists a successful choice. An unknown name falls back to the system theme and returns failure without changing the stored selection (theme.ts setTheme).
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 []string, opts *extension.ExtensionWidgetOptions)
SetWidget sets a widget of text lines above or below the editor; nil lines remove it (types.ts:188 setWidget).
func (*ExtUIContext) SetWidgetFactory ¶
func (u *ExtUIContext) SetWidgetFactory(key string, factory extension.WidgetFactory, opts *extension.ExtensionWidgetOptions)
SetWidgetFactory sets the widget factory builds above or below the editor; a nil factory removes it (types.ts:189 setWidget's second overload).
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) ShowRemoteOverlay ¶
func (u *ExtUIContext) ShowRemoteOverlay(opts extension.RemoteOverlayOptions, host extension.RemoteOverlayHost) (extension.RemoteOverlayHandle, <-chan struct{}, bool)
ShowRemoteOverlay is Pi's TUI.showOverlay (tui.ts:729-826) for a component a subprocess factory or component shows through its tui argument. The overlay goes on the stack at once, takes focus unless it is non-capturing, and has no ui.custom call behind it: its handle's hide ends it (Pi removes the entry and focuses the topmost visible overlay or the entry's preFocus), as does Close, which the bridge calls when the extension's connection ends. A hideOverlay that pops it, as in Pi, leaves the handle in place, and a later hide is a no-op on the stack that still ends it. Its own goroutine delivers its keys while it holds focus.
func (*ExtUIContext) Theme ¶
func (u *ExtUIContext) Theme() extension.Theme
func (*ExtUIContext) UnregisterSprites ¶
func (u *ExtUIContext) UnregisterSprites(owner string)
UnregisterSprites removes the sprites of an extension that unloaded; the header redraws in case it showed one.
type ExtensionCommandLister ¶
type ExtensionCommandLister interface {
Commands() []extension.ResolvedCommand
}
ExtensionCommandLister is the extension runner surface the command catalog reads.
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 and each extension's tools in registration 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. Flags have no recorded registration order and are walked by name.
type ExtensionContext ¶
type ExtensionContext struct {
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 ExtensionEditorComponent ¶
ExtensionEditorComponent is the multi-line editor overlay of ctx.ui.editor() and the /tree summary prompt (extension-editor.ts ExtensionEditorComponent).
Layout: DynamicBorder, Spacer(1), Text(accent title), [Spacer(1), Text(description)], Spacer(1), Editor, Text(external editor status, empty unless an external editor failed), Spacer(1), Text(hint), Spacer(1), DynamicBorder.
Ports packages/coding-agent/src/modes/interactive/components/extension-editor.ts
func NewExtensionEditorComponent ¶
func NewExtensionEditorComponent(ui tui.TUI, keybindings *KeybindingsManager, title, prefill string, onSubmit func(string), onCancel func(), options *ExtensionEditorOptions, externalEditorCommand string) *ExtensionEditorComponent
NewExtensionEditorComponent is extension-editor.ts constructor(tui, keybindings, title, prefill, onSubmit, onCancel, options, externalEditorCommand). onSubmit receives the editor's text when Enter submits; onCancel runs on the cancel key. After either has run the component ignores input, because its caller removes it in the same turn. options may be nil. externalEditorCommand is what the handoff bound by ExtensionEditorComponent.SetExternalEditor receives; empty leaves the choice to the handoff.
func (*ExtensionEditorComponent) Focused ¶
func (c *ExtensionEditorComponent) Focused() bool
Focused reports the Focusable flag (extension-editor.ts get focused).
func (*ExtensionEditorComponent) HandleInput ¶
func (c *ExtensionEditorComponent) HandleInput(data string)
HandleInput is extension-editor.ts handleInput: the cancel key calls onCancel, the external-editor key opens the handoff, and everything else goes to the editor.
func (*ExtensionEditorComponent) SetExternalEditor ¶
func (c *ExtensionEditorComponent) SetExternalEditor(open func(command, content string, apply func(string), report func(message string)))
SetExternalEditor binds the terminal owner's asynchronous external-editor handoff, which hands the terminal to a child running command on content. A successful completion calls apply, which replaces the editor's text without submitting the dialog. Upstream does the handoff inside the component (ui.stop, editInExternalEditor, ui.start); the terminal owner here also owns raw mode and the input reader, so it runs the child.
func (*ExtensionEditorComponent) SetFocused ¶
func (c *ExtensionEditorComponent) SetFocused(focused bool)
SetFocused implements Focusable: the flag propagates to the inner editor, which emits the hardware-cursor marker only while focused (extension-editor.ts set focused).
type ExtensionEditorOptions ¶
type ExtensionEditorOptions struct {
tui.EditorOptions
Description string
}
ExtensionEditorOptions is extension-editor.ts ExtensionEditorOptions: the Editor's options and an optional description shown between the title and the editor.
type ExtensionOAuthConfig ¶
type ExtensionOAuthConfig = extension.ExtensionOAuthConfig
ExtensionOAuthConfig is the extension host's OAuth configuration for a registered provider (provider-composer.ts ExtensionOAuthConfig).
type ExtensionSessionInfoMemo ¶
type ExtensionSessionInfoMemo struct {
// contains filtered or unexported fields
}
ExtensionSessionInfoMemo keeps the encoding of ExtensionSessionInfo between state pushes. The info is a pure function of the values read live on each call (cwd, session directory, whether the session persists, the header), so the memo is keyed by all of them and a change to any one rebuilds it.
func (*ExtensionSessionInfoMemo) Encoded ¶
func (m *ExtensionSessionInfoMemo) Encoded(view ExtensionSessionView) (json.RawMessage, error)
Encoded returns the encoding of ExtensionSessionInfo(view).
type ExtensionSessionView ¶
ExtensionSessionView names the session an extension reads and the facts the session file does not hold: the session manager's cwd, its session directory, and whether it persists (upstream SessionManager cwd, sessionDir and persist).
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 ExtensionToolLister ¶
type ExtensionToolLister interface {
Tools() []extension.RegisteredTool
ToolSourceInfo(toolName string) (extension.SourceInfo, bool)
}
ExtensionToolLister is the extension runner surface ExtensionToolInfos reads.
type ExtensionWarning ¶
type ExtensionWarning struct{ Path, Warning string }
ExtensionWarning is a {path, warning} entry of types.ts LoadExtensionsResult.warnings.
func ExtensionPackageWarnings ¶
func ExtensionPackageWarnings(packageRoots []string) ([]ExtensionWarning, error)
ExtensionPackageWarnings warns about an extension package whose package.json lists host-provided packages under `dependencies`. It reads each package root once, in first-seen order, and fails when a manifest cannot be parsed. packageRoots holds the PathMetadata.packageRoot of each extension path; a top-level extension and a local file source have none. Ports .upstream/current/packages/coding-agent/src/core/resource-loader.ts:66-93 (collectExtensionPackageWarnings).
func MergeExtensionWarnings ¶
func MergeExtensionWarnings(existing, added []ExtensionWarning) []ExtensionWarning
MergeExtensionWarnings keeps one warning per path: the last one, at the position of the first. Ports .upstream/current/packages/coding-agent/src/core/resource-loader.ts:95-102 (mergeExtensionWarnings).
type ExternalEditorFailure ¶
ExternalEditorFailure is the error of an editor that did not complete: it could not be started, exited non-zero, or was signaled. Message is the status text Pi shows for it. Error keeps the longer text of the underlying failure.
func (*ExternalEditorFailure) Error ¶
func (f *ExternalEditorFailure) Error() string
func (*ExternalEditorFailure) Unwrap ¶
func (f *ExternalEditorFailure) Unwrap() error
type FetchUpdateManifestOptions ¶
type FetchUpdateManifestOptions struct {
Retry bool
}
FetchUpdateManifestOptions selects explicit-update transport retries. Startup checks leave Retry false.
type FileEntry ¶
type FileEntry = sessionentry.FileEntry
FileEntry is one record of a session file: the header (SessionHeader) or an entry (SessionEntry) (session-manager.ts FileEntry).
func LoadEntriesFromFile ¶
Ports packages/coding-agent/src/core/session-manager.ts (loadEntriesFromFile). LoadEntriesFromFile skips malformed and JSON-falsy lines and requires a session header before accepting records.
func ParseSessionEntries ¶
ParseSessionEntries splits JSONL content into its records, in order. Ports packages/coding-agent/src/core/session-manager.ts (parseSessionEntries): the content is trimmed and split on "\n", a line that is not valid JSON, including a blank one, is skipped (only JSON whitespace may surround a record, so a line led by U+00A0 is skipped). Unlike LoadEntriesFromFile it keeps a record whose JSON value is falsy (null, false, 0, ""), because Pi pushes whatever JSON.parse returns.
type FindInitialModelOptions ¶
type FindInitialModelOptions struct {
ScopedModels []ScopedModel
IsContinuing bool
DefaultProvider string
DefaultModelId string
DefaultThinkingLevel string
ModelThinkingLevels map[string]string
ModelRuntime InitialModelRuntime
}
FindInitialModelOptions carries selection inputs without owning a Model Runtime, refreshing its snapshots, or resolving credentials. Empty optional thinking strings represent no selection.
type FirstTimeSetupComponent ¶
FirstTimeSetupComponent is the first-time setup dialog: theme, sprite and analytics opt-in. pig divergence (D88): the dialog's logo is the pig head of the sprite in view, not Pi's SETUP_LOGO_LINES, and a sprite step follows the theme step; its options are the built-in sprites, then the extension-registered ones (piglogin.All).
func NewFirstTimeSetupComponent ¶
func NewFirstTimeSetupComponent(options FirstTimeSetupOptions) *FirstTimeSetupComponent
NewFirstTimeSetupComponent builds the dialog over the sprites offered at construction, starting on the active sprite. pig additive (D92): pig-login owns /sprite, so with it stripped there are no sprites to offer and no sprite step.
func (*FirstTimeSetupComponent) Done ¶
func (c *FirstTimeSetupComponent) Done() bool
Done reports whether the dialog was submitted or skipped.
func (*FirstTimeSetupComponent) HandleInput ¶
func (c *FirstTimeSetupComponent) HandleInput(data string)
HandleInput moves, advances, submits or cancels.
func (*FirstTimeSetupComponent) Invalidate ¶
func (c *FirstTimeSetupComponent) Invalidate()
Invalidate rebuilds on theme changes, e.g. when the system theme receives the terminal's colors.
type FirstTimeSetupOptions ¶
type FirstTimeSetupOptions struct {
OnThemePreview func(themeName string)
OnSubmit func(result FirstTimeSetupResult)
OnCancel func()
}
FirstTimeSetupOptions are the dialog's callbacks.
type FirstTimeSetupResult ¶
FirstTimeSetupResult is the dialog's submitted choice.
func ShowFirstTimeSetup ¶
func ShowFirstTimeSetup(settings FirstTimeSetupSettings, opts StartupUIOptions) (*FirstTimeSetupResult, error)
ShowFirstTimeSetup shows the first-time setup dialog on its own screen before the interactive TUI starts, as Pi's showFirstTimeSetup does (cli/startup-ui.ts:182-218, main.ts:672-676), and persists a submitted result: the theme and analytics opt-in in settings, and the sprite exactly as /sprite set saves it. It returns the submitted result, or nil when setup was skipped. A settings write failure is recorded by the settings manager, not returned, as Pi's queued writes are. pig divergence (D88): the sprite step offers the built-in sprites; extensions are not loaded yet, so their sprites are chosen later with /sprite.
type FirstTimeSetupSettings ¶
type FirstTimeSetupSettings interface {
SetTheme(name string) error
SetEnableAnalytics(enabled bool) error
}
FirstTimeSetupSettings is the settings store a submitted first-time setup writes.
type FooterComponent ¶
type FooterComponent struct {
// (footer.ts footerData; footer-data-provider.ts).
*FooterDataProvider
// contains filtered or unexported fields
}
FooterComponent 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 NewFooterComponent ¶
func NewFooterComponent(model *ai.Model, agentName string, timings *agent.Recorder) *FooterComponent
NewFooterComponent creates a FooterComponent bound to the given model + agent. timings may be nil; cost/elapsed columns are then suppressed.
func NewFooterComponentForSession ¶
func NewFooterComponentForSession(session FooterSession, footerData *FooterDataProvider) *FooterComponent
NewFooterComponentForSession is Pi's FooterComponent constructor (footer.ts:68-71): a footer that reads usage totals and the routed model from session and its cwd, git branch, extension statuses and provider count from footerData. The model is set with SetModel.
func (*FooterComponent) GetWorkingMessage ¶
func (s *FooterComponent) GetWorkingMessage() string
GetWorkingMessage returns the current custom working message or "".
func (*FooterComponent) GitBranch ¶
func (s *FooterComponent) GitBranch() string
GitBranch returns the cached git branch, empty outside a repo.
func (*FooterComponent) ProviderCount ¶
func (s *FooterComponent) ProviderCount() int
ProviderCount returns the number of authenticated, reachable providers.
func (*FooterComponent) Render ¶
func (s *FooterComponent) Render(width int) []string
Render returns the footer lines (normally 2 plus keyed statuses).
func (*FooterComponent) ResetContextUsage ¶
func (s *FooterComponent) ResetContextUsage()
ResetContextUsage clears the context-window column before a transcript rebuild re-reads it from the branch.
func (*FooterComponent) SetAgentName ¶
func (s *FooterComponent) SetAgentName(name string)
SetAgentName updates the agent persona label.
func (*FooterComponent) SetAutoCompactEnabled ¶
func (s *FooterComponent) SetAutoCompactEnabled(enabled bool)
SetAutoCompactEnabled updates the "(auto)" indicator.
func (*FooterComponent) SetContextUsage ¶
func (s *FooterComponent) 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 (*FooterComponent) SetCwd ¶
func (s *FooterComponent) SetCwd(cwd string)
SetCwd binds the footer and its branch watcher to the repository present at initialization.
func (*FooterComponent) SetExtensionStatus ¶
func (s *FooterComponent) 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 (*FooterComponent) SetModel ¶
func (s *FooterComponent) 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 (*FooterComponent) SetName ¶
func (s *FooterComponent) SetName(name string)
SetName updates the session name shown in the footer.
func (*FooterComponent) SetProviderCount ¶
func (s *FooterComponent) 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 (*FooterComponent) SetSession ¶
func (s *FooterComponent) SetSession(session FooterSession)
SetSession points the footer at another session (footer.ts setSession); the next render reads that session's totals and routed model. A nil session reads neither.
func (*FooterComponent) SetSubscriptionResolver ¶
func (s *FooterComponent) SetSubscriptionResolver(resolve func(*ai.Model) bool)
SetSubscriptionResolver installs the "(sub)" decision used by SetModel.
func (*FooterComponent) SetSuppressedByExtFooter ¶
func (s *FooterComponent) 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 (*FooterComponent) SetThinkingLevel ¶
func (s *FooterComponent) SetThinkingLevel(level string)
SetThinkingLevel updates the thinking level display.
func (*FooterComponent) SetTurnContextUsage ¶
func (s *FooterComponent) 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 (*FooterComponent) SetUsingSubscription ¶
func (s *FooterComponent) SetUsingSubscription(v bool)
SetUsingSubscription updates the OAuth subscription indicator. When true, cost display shows "(sub)". Mirrors upstream footer.ts:128.
func (*FooterComponent) SetWorking ¶
func (s *FooterComponent) SetWorking(b bool)
SetWorking flips the spinner column on/off.
func (*FooterComponent) SetWorkingMessage ¶
func (s *FooterComponent) 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 FooterDataProvider ¶
type FooterDataProvider struct {
// contains filtered or unexported fields
}
FooterDataProvider is the data a footer reads about its surroundings (footer-data-provider.ts FooterDataProvider): the working directory and the git branch of the repository bound to it, the statuses extensions set, the number of available providers, and the branch-change subscribers. A footer built with NewFooterComponentForSession shares one provider with the host that feeds it.
Ports packages/coding-agent/src/core/footer-data-provider.ts (FooterDataProvider).
func NewFooterDataProvider ¶
func NewFooterDataProvider() *FooterDataProvider
NewFooterDataProvider creates a provider bound to no repository, with no statuses and no providers.
func (*FooterDataProvider) Dispose ¶
func (d *FooterDataProvider) Dispose()
Dispose is footer-data-provider.ts dispose (:187), which FooterComponent.dispose (footer.ts:93) leaves the cleanup to: it stops the git branch watcher and drops the OnBranchChange subscribers.
func (*FooterDataProvider) GetAvailableProviderCount ¶
func (d *FooterDataProvider) GetAvailableProviderCount() int
GetAvailableProviderCount returns the number of authenticated, reachable providers (getAvailableProviderCount).
func (*FooterDataProvider) GetExtensionStatuses ¶
func (d *FooterDataProvider) GetExtensionStatuses() map[string]string
GetExtensionStatuses returns a snapshot of all extension statuses (getExtensionStatuses).
func (*FooterDataProvider) GetGitBranch ¶
func (d *FooterDataProvider) GetGitBranch() string
GetGitBranch returns the cached git branch, empty outside a repo (getGitBranch).
func (*FooterDataProvider) ObserveChange ¶
func (d *FooterDataProvider) ObserveChange(observe func()) func()
ObserveChange registers observe to run after the git branch or the number of available providers changed, the values a footer reads that no extension call sets. observe runs on the goroutine that made the change and must return at once. The returned function removes it and can be called repeatedly.
func (*FooterDataProvider) OnBranchChange ¶
func (d *FooterDataProvider) OnBranchChange(fn func()) func()
OnBranchChange subscribes to git-branch updates and returns the unsubscribe function (onBranchChange).
func (*FooterDataProvider) SetCwd ¶
func (d *FooterDataProvider) SetCwd(cwd string)
SetCwd binds the provider to the repository present at cwd, resolving its branch.
func (*FooterDataProvider) SetExtensionStatus ¶
func (d *FooterDataProvider) SetExtensionStatus(key, text string)
SetExtensionStatus sets, or with empty text clears, a keyed status entry (setExtensionStatus, clearExtensionStatuses).
func (*FooterDataProvider) SetProviderCount ¶
func (d *FooterDataProvider) SetProviderCount(n int)
SetProviderCount records the number of authenticated, reachable providers (setAvailableProviderCount).
type FooterSession ¶
type FooterSession interface {
SessionManager() *Session
RoutedModelSelection() *RoutedModelSelection
}
FooterSession is the members of Pi's AgentSession that FooterComponent reads (footer.ts:103-107, :241): sessionManager, whose entries carry the all-entry usage totals (getSessionStats), and routedModel, the physical model the latest response was routed to. Go's AgentSession is coding.Session, which imports this package, so the footer takes this consumer-owned interface of exactly those two members, and package coding asserts that *coding.Session implements it.
type FullscreenExitOutput ¶
type FullscreenExitOutput string
FullscreenExitOutput selects what a fullscreen exit prints (settings-manager.ts:55).
const ( FullscreenExitOutputTranscript FullscreenExitOutput = "transcript" FullscreenExitOutputResumeHint FullscreenExitOutput = "resume-hint" )
type GraphArgs ¶
type GraphArgs []json.RawMessage
GraphArgs are the positional arguments of a session graph call: a JSON array, which may stop early, whose members may be null for Pi's undefined.
func ParseGraphArgs ¶
func ParseGraphArgs(raw json.RawMessage) (GraphArgs, error)
ParseGraphArgs decodes the positional arguments of a session graph call.
func (GraphArgs) Raw ¶
func (a GraphArgs) Raw(i int) json.RawMessage
Raw is argument i, nil when Pi's undefined or null.
type GraphProjectTrustStore ¶
type GraphProjectTrustStore struct {
// contains filtered or unexported fields
}
GraphProjectTrustStore is a ProjectTrustStore an extension constructed.
func NewGraphProjectTrustStore ¶
func NewGraphProjectTrustStore(op string, raw json.RawMessage) (*GraphProjectTrustStore, error)
NewGraphProjectTrustStore builds `new ProjectTrustStore(agentDir)`.
func (*GraphProjectTrustStore) Call ¶
func (g *GraphProjectTrustStore) Call(_ context.Context, method string, raw json.RawMessage) (any, error)
Call runs a ProjectTrustStore method.
type GraphSessionManager ¶
type GraphSessionManager struct {
// contains filtered or unexported fields
}
GraphSessionManager is a SessionManager an extension constructed.
func NewGraphSessionManager ¶
func NewGraphSessionManager(op string, raw json.RawMessage) (*GraphSessionManager, error)
NewGraphSessionManager builds the SessionManager of Pi's static factory op (create, open, continueRecent, inMemory, forkFrom).
func NewGraphSessionManagerOf ¶
func NewGraphSessionManagerOf(session *Session) *GraphSessionManager
NewGraphSessionManagerOf is the SessionManager object of a session log that already exists: AgentSession.sessionManager as an extension holds it.
func (*GraphSessionManager) Call ¶
func (g *GraphSessionManager) Call(_ context.Context, method string, raw json.RawMessage) (any, error)
Call runs a SessionManager method.
func (*GraphSessionManager) Session ¶
func (g *GraphSessionManager) Session() *Session
Session is the log the object holds. A session created from the object shares it, as Pi's createAgentSession shares the SessionManager it is given.
type GraphSettingsManager ¶
type GraphSettingsManager struct {
// contains filtered or unexported fields
}
GraphSettingsManager is a SettingsManager an extension constructed.
func NewGraphSettingsManager ¶
func NewGraphSettingsManager(scope subprocess.SessionGraphScope, op string, raw json.RawMessage) (*GraphSettingsManager, error)
NewGraphSettingsManager builds the SettingsManager of Pi's static factory op (create, inMemory, fromStorage).
func (*GraphSettingsManager) Call ¶
func (g *GraphSettingsManager) Call(_ context.Context, method string, raw json.RawMessage) (any, error)
Call runs a SettingsManager method.
func (*GraphSettingsManager) Manager ¶
func (g *GraphSettingsManager) Manager() *SettingsManager
Manager is the settings object the handle names. A session created from it shares it, as Pi's createAgentSession shares the SettingsManager it is given.
type HandleReads ¶
type HandleReads struct{ *Session }
HandleReads is a Session whose entry reads return each message entry that is not resident as a sessionentry.LazyEntry, for the readers in this module that read entries only through the error-returning sessionentry funnel (ReadRaws, MaterializeAll): RPC get_entries and get_tree, extension session reads and branch summary collection. It is never handed to code outside the module: the Session's own GetEntries, GetBranch, GetTree and GetEntry return decoded entries. TestLazyEntriesLeaveOnlyByTheReviewedRoutes keeps its uses, and those of the unexported handle reads, to the files that consume them so.
func (HandleReads) GetBranch ¶
func (r HandleReads) GetBranch(fromID ...string) []SessionEntry
GetBranch is Session.GetBranch with lazy message entries.
func (HandleReads) GetEntries ¶
func (r HandleReads) GetEntries() []SessionEntry
GetEntries is Session.GetEntries with lazy message entries.
func (HandleReads) GetEntry ¶
func (r HandleReads) GetEntry(id string) (SessionEntry, bool)
GetEntry is Session.GetEntry with a lazy message entry.
func (HandleReads) GetTree ¶
func (r HandleReads) GetTree() []*SessionTreeNode
GetTree is Session.GetTree with lazy message entries.
type HelpCommandInfo ¶
type HelpCommandInfo struct {
Name string
Aliases []string
Description string
Source SlashCommandSource
}
HelpCommandInfo is the user-facing summary used by `/help`. It is not upstream's SlashCommandInfo, which is SlashCommandInfo.
type HostActionBinder ¶
HostActionBinder is what a mode's extension bridge offers the host actions bound on it (subprocess.UIBridge.SetHostAction).
type InitialModelResult ¶
type InitialModelResult struct {
Model *RuntimeModel
ThinkingLevel string
FallbackMessage string
}
InitialModelResult preserves selection-dependent thinking. Provider-default, first-available, and no-model fallbacks use DefaultThinkingLevel, not the caller's saved level.
func FindInitialModel ¶
func FindInitialModel(options FindInitialModelOptions) (InitialModelResult, error)
FindInitialModel selects new-session scope, authenticated saved default, or an available fallback in that order.
type InitialModelRuntime ¶
type InitialModelRuntime interface {
ModelResolverRuntime
GetModel(providerID, modelID string) *RuntimeModel
GetAvailableSnapshot() []RuntimeModel
}
InitialModelRuntime keeps exact catalog lookup and the available snapshot separate. A configured provider may have models that are absent from the available snapshot.
type InteractiveForkResult ¶
InteractiveForkResult is the outcome of a runtime fork. SelectedText is absent when the fork is at an entry, and for a cancelled fork.
type InteractiveMode ¶
type InteractiveMode struct {
// contains filtered or unexported fields
}
InteractiveMode runs the full interactive TUI session.
func NewInteractiveMode ¶
func NewInteractiveMode(runtimeHost InteractiveRuntime, options InteractiveModeOptions) *InteractiveMode
NewInteractiveMode creates an interactive session over the runtime host that created its Session, as Pi's constructor(runtimeHost, options = {}) does. A non-nil runtimeHost owns Session replacement: new, resume, fork, clone and import build the destination Session through its factory, and options.ReplacementResources supplies the destination build's options. A nil runtimeHost replaces the Session in place.
upstream: packages/coding-agent/src/modes/interactive/interactive-mode.ts:608
func (*InteractiveMode) ClearEditor ¶
func (m *InteractiveMode) ClearEditor()
requestRender coalesces a render on the current renderer, race-safe like renderNow. ClearEditor empties the editor and re-renders; it shows no status.
upstream: interactive-mode.ts:4578 (clearEditor)
func (*InteractiveMode) Init ¶
func (m *InteractiveMode) Init(ctx context.Context) (err error)
Init is upstream's init(): it builds the terminal UI, binds the session, emits session_start and renders the startup transcript. It returns nil without work once initialized. A failure leaves the teardowns registered so far for Stop. The caller owns Stop; Run calls both.
func (*InteractiveMode) RoutedModelSelection ¶
func (m *InteractiveMode) RoutedModelSelection() *RoutedModelSelection
RoutedModelSelection reads the physical model the current session's latest response was routed to (AgentSession.routedModel).
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) SessionManager ¶
func (m *InteractiveMode) SessionManager() *Session
SessionManager is the current session's log (AgentSession.sessionManager); the mode is the footer's session so that the footer follows a Session replacement.
func (*InteractiveMode) ShowPackageUpdateNotification ¶
func (m *InteractiveMode) ShowPackageUpdateNotification(packages []string)
ShowPackageUpdateNotification adds the bordered "Package Updates Available" notice naming the packages to the chat.
upstream: interactive-mode.ts:4627 (showPackageUpdateNotification)
func (*InteractiveMode) ShutdownFromSignal ¶
func (m *InteractiveMode) ShutdownFromSignal()
ShutdownFromSignal emits session_shutdown before requesting owner-loop teardown. Concurrent callers join ongoing cleanup, and repeated calls do not emit again.
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.
func (*InteractiveMode) Stop ¶
func (m *InteractiveMode) Stop(fullscreenExitOutput ...FullscreenExitOutput) error
Stop is upstream's stop(): it releases everything Init and Run registered, in reverse order, and marks the mode uninitialized. It is safe to call more than once, and after a failed Init it releases what that Init built. The optional fullscreenExitOutput replaces the setting for this stop, as upstream's parameter does. The returned error joins the teardown failures.
type InteractiveModeOptions ¶
type InteractiveModeOptions struct {
CWD string
AgentDir string
Model *ai.Model
Settings Settings
// InitialThemeSetting selects a theme for this run without changing the SettingsManager. A non-nil empty name is a selection that fails and falls back to dark. Explicit selections replace it; absent selections follow the current manager.
InitialThemeSetting *string
// TuiMode selects "regular" or "fullscreen" for this run without changing the SettingsManager. Empty captures Settings.TuiMode at construction; only a live mode switch changes it afterwards.
TuiMode string
// Frontend is the Piglet frontend member that may draw this run in place
// of the ANSI renderer; nil in Stock PiG.
// pig additive (D91): Pi has no frontend member.
Frontend frontend.Frontend
// Terminal is the terminal the renderer drives (interactive-mode.ts:447 `terminal?: Terminal`, passed to createInteractiveTui at :626). Nil selects the process terminal.
Terminal tui.Terminal
// SettingsManager provides read/write access to global settings.
// Wired by main.go via coding.AgentSessionServices.
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{}
// InitialActiveToolNames is the --tools list in the caller's order (upstream initialActiveToolNames, sdk.ts:272-276):
// a rebuild of the tools (/reload, /new, /resume) activates these first, in this order, then the tools AllowedTools matches.
InitialActiveToolNames []string
// 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{}
// ToolRegistryAllowed is the --tools allowlist bounding the tool registry
// pi.getAllTools() reports (upstream _allowedToolNames): nil admits every
// tool, an empty map none. Unlike AllowedTools, active-tool changes never
// modify it.
ToolRegistryAllowed 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
// CLIPromptTemplatePaths are the local --prompt-template paths, resolved once against the launch directory as main.ts
// resolves them. Startup, /reload and a runtime rebind report each one that does not exist (resource-loader.ts:615-626).
CLIPromptTemplatePaths []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 resolved theme files/directories in resource precedence order.
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 stock footer and extension usage reads.
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)
// DefaultModelPerProvider shares the startup resolver's provider defaults with /login.
DefaultModelPerProvider map[string]string
// ModelLookup resolves a provider/model identity through the Session-owned runtime.
ModelLookup func(providerID, modelID string) *ai.Model
ModelCatalog func(providerID ...string) []*ai.Model
// ModelClassify is the Session-owned runtime classify an extension's ctx.modelRegistry.classify reaches.
ModelClassify func(context.Context, *ai.ClassifierModel, ai.ClassifierContext, ...ai.ModelsClassifierOptions) ai.ClassifierResult
// ModelGenerateImages is the Session-owned runtime generateImages an extension's ctx.modelRegistry.generateImages reaches.
ModelGenerateImages func(context.Context, *ai.ImageModel, ai.ImagesContext, ...ai.ModelsImagesOptions) ai.AssistantImages
// 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
// SessionStartEvent is the factory-selected startup/new/resume/fork event for the current Session.
SessionStartEvent *extension.SessionStartEvent
// 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
// 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 InteractiveModeOptions.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
// SkillDiagnostics retains ordered load-time collisions for the startup listing.
SkillDiagnostics []extension.ResourceDiagnostic
// 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 automatic skill discovery; explicitly selected and extension-discovered paths still load on reload.
NoSkills bool
// ContextFiles lists the loaded AGENTS.md/CLAUDE.md project context files.
// The loaded-resources [Context] section lists them after
// SystemPromptSourcePaths.
ContextFiles []ContextFile
// SystemPromptSourcePaths are the existing files the system prompt and
// then each appended system prompt were read from, as upstream
// getSystemPromptSource and getAppendSystemPromptSources report them.
SystemPromptSourcePaths []string
// ContextFilesTrustedOnly marks a run that withholds an untrusted project's context files, and that warns of them.
// pig additive (D211).
ContextFilesTrustedOnly bool
// ReplacementResources returns the cwd-bound options of the build that owns session.
ReplacementResources func(session InteractiveSessionHandle) InteractiveReplacement
// 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
// TerminateExtensionProcesses, when set, kills every extension process without running extension callbacks. It runs before an emergency exit on a dead terminal, which skips orderly shutdown.
TerminateExtensionProcesses func()
// 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
// ExplicitBuiltinPaths are the `builtin:<name>` paths of the -e arguments; those built-ins load before the configured extensions.
ExplicitBuiltinPaths []string
// 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
// AutoTrustOnReloadCwd is the Session cwd whose project trust a later /reload saves once the project gains trust-requiring resources. It is empty when a trust override was given or the cwd already had them.
AutoTrustOnReloadCwd string
// MigratedProviders names the providers whose legacy credentials this start moved to auth.json.
MigratedProviders []string
// ModelFallbackMessage is the warning shown at startup when the saved Session model could not be restored or no model is available (upstream modelFallbackMessage).
ModelFallbackMessage 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 coding/cli/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
}
InteractiveModeOptions configures the interactive mode.
type InteractiveReplacement ¶
type InteractiveReplacement struct {
CWD string
SessionDir string
Settings Settings
SettingsManager *SettingsManager
ModelRegistry *ModelRegistry
SystemPrompt string
SystemPromptOptions extension.BuildSystemPromptOptions
AllowedTools map[string]struct{}
ActiveBuiltinTools map[string]struct{}
InitialActiveToolNames []string
ExcludedTools map[string]struct{}
ToolRegistryAllowed map[string]struct{}
NoBuiltinTools bool
PromptPaths []string
CLIPromptTemplatePaths []string
ThemePaths []string
SkillPaths []string
Skills []*SkillDef
SkillDiagnostics []extension.ResourceDiagnostic
ContextFiles []ContextFile
SystemPromptSourcePaths []string
RebuildSystemPrompt func(skills []*SkillDef, contextFiles []ContextFile) (string, extension.BuildSystemPromptOptions)
ResourceSourceInfo func() map[string]ResourceSourceInfo
ReloadResources func() ReloadResourceSnapshot
ExtensionRunner *inproc.Runner
SessionStartEvent extension.SessionStartEvent
// ExtensionConflicts are the tool and flag conflicts of the build's final extension set, which Pi lists with the extension load errors.
ExtensionConflicts []ExtensionConflict
BuiltinExtensions []extension.Extension
ExplicitBuiltinPaths []string
ReloadBuiltinExtensions func() []extension.Extension
SubprocessUIBridge SubprocessUIBridge
SubprocessHost SubprocessHost
ModelLookup func(providerID, modelID string) *ai.Model
ModelCatalog func(providerID ...string) []*ai.Model
ModelClassify func(context.Context, *ai.ClassifierModel, ai.ClassifierContext, ...ai.ModelsClassifierOptions) ai.ClassifierResult
ModelGenerateImages func(context.Context, *ai.ImageModel, ai.ImagesContext, ...ai.ModelsImagesOptions) ai.AssistantImages
RequestAuthRuntime *RequestAuthRuntime
}
InteractiveReplacement carries the options of a replacement Session's cwd-bound build, as Pi reads them from the new Session's services. The mode applies it before it rebinds to the Session.
type InteractiveRuntime ¶
type InteractiveRuntime interface {
NewSession(ctx context.Context, options *extension.NewSessionOptions) (extension.CancelledResult, error)
// SwitchSession opens path and replaces the Session. projectTrustUI supplies the UI of the destination's project trust prompt, as Pi's projectTrustContextFactory does.
SwitchSession(ctx context.Context, path, cwdOverride string, projectTrustUI func(cwd string) extension.ProjectTrustContext, options *extension.SwitchSessionOptions) (extension.CancelledResult, error)
Fork(ctx context.Context, entryID string, options *extension.ForkOptions) (InteractiveForkResult, error)
ImportFromJsonl(ctx context.Context, path, cwdOverride string) (extension.CancelledResult, error)
// ExtensionCommandActions returns the command actions of session with new, fork and switch routed through the runtime.
ExtensionCommandActions(session InteractiveSessionHandle) extension.CommandActions
// EmitQuitShutdown emits session_shutdown for quit once; closing the runtime does not repeat it.
EmitQuitShutdown()
// SetBeforeSessionReplacement installs the drain that runs after a replacement is approved and before the outgoing Session aborts.
SetBeforeSessionReplacement(drain func(context.Context) error)
// SetBeforeSessionInvalidate installs the synchronous hook that runs after session_shutdown and before the outgoing Session's extension contexts go stale.
SetBeforeSessionInvalidate(hook func())
// SetRebindSession installs the awaited callback that runs once the replacement Session is installed.
SetRebindSession(rebind func(ctx context.Context, session InteractiveSessionHandle) error)
}
InteractiveRuntime is the Session replacement contract InteractiveMode needs from the runtime host that created its Session. *coding.Runtime satisfies it through the adapter in cmd/pig; the interface exists because internal/codingagent cannot import coding.
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
// RecordUserBashResult records a user `!` command result as upstream recordBashResult: appended to the
// Session and live context when idle, queued until the run ends while one streams. It returns the immediate
// persistence failure.
RecordUserBashResult(command string, result BashResult, excludeFromContext bool) error
// Events returns the agent's streaming event channel. Used by
// processAgentEvents to drive live UI updates.
Events() <-chan agent.AgentEvent
// IsIdle and WaitForIdle observe the Session-owned operation, including work an extension started.
IsIdle() bool
WaitForIdle(context.Context) error
// SetModelOnMain dispatches the synchronous state mutation to the owner loop, then waits for extension notifications on the caller. The dispatcher may reject a superseded mutation. The auth check and notifications end with ctx.
SetModelOnMain(context.Context, *ai.Model, ModelMutationOptions, func(func() error) error) error
// BeginModelCycleOnMain applies the next model from the current scope or available models on the owner loop and returns its extension notifications as a completion to run once off the loop; they end with ctx. A nil result means there is nothing to cycle to.
BeginModelCycleOnMain(context.Context, string, ModelMutationOptions) (*ModelCycleResult, func(), error)
// LastAssistantText is the trimmed text of the last assistant message, nil when it has none (agent-session.ts getLastAssistantText).
LastAssistantText() *string
// ScopedModels returns the cycling scope. An empty list means all available models.
ScopedModels() []extension.ScopedModel
// SetScopedModels replaces the cycling scope.
SetScopedModels([]extension.ScopedModel)
// AvailableModelSnapshot is the Session ModelRuntime's available models, bound to their backends (Pi's session.modelRuntime.getAvailableSnapshot()). Cycling scope entries come from it.
AvailableModelSnapshot() []*ai.Model
// ExtensionCompact is the compact action Pi binds for extensions: it starts a manual compaction without waiting, reports the result to options.OnComplete and a failure to options.OnError, and drops the outcome without callbacks.
ExtensionCompact(*extension.CompactOptions)
// ExtensionSetModel answers an extension's pi.setModel: false without configured credentials, otherwise it switches as SetModel does and answers true.
ExtensionSetModel(context.Context, *ai.Model) (bool, error)
// SetThinkingLevel applies and records reasoning without changing defaults unless Persist is set.
SetThinkingLevel(ai.ModelThinkingLevel, ...ModelMutationOptions) error
// SetThinkingLevelOnMain dispatches the synchronous state mutation to the owner loop, then runs the thinking_level_select notification on the caller. The dispatcher may reject a superseded mutation.
SetThinkingLevelOnMain(ai.ModelThinkingLevel, ModelMutationOptions, func(func() error) error) error
// SetSessionName persists and publishes a sanitized Session name.
SetSessionName(string) error
// StreamModel starts a mode-independent model operation through the
// Session-owned runtime.
StreamModel(context.Context, *ai.Model, ai.Context, ai.StreamOptions) *ai.AssistantMessageEventStream
// Compact runs manual compaction like upstream AgentSession.compact(): it aborts the active run, rejects a session with nothing to compact, and reports both outcomes through the compaction events.
Compact(ctx context.Context, customInstructions string) (*CompactionResult, error)
// 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()
// RetryAttempt is the current automatic retry attempt, 0 when not
// retrying. Mirrors upstream AgentSession.retryAttempt.
RetryAttempt() int
// ExportToJsonl writes the current branch as JSONL and returns the path. Mirrors upstream AgentSession.exportToJsonl.
ExportToJsonl(outputPath string) (string, error)
// 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, options NavigateTreeOptions) (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()
// DeferCustomMessage holds a custom message an extension sent with triggerTurn false while a run streams, until the turn's tool results are complete. It reports false when no run is active.
DeferCustomMessage(agent.AgentMessage) bool
// HasDeferredCustomMessages reports whether a custom message waits for the end of its turn.
HasDeferredCustomMessages() bool
// FlushDeferredCustomMessages appends the custom messages held for the end of a turn.
FlushDeferredCustomMessages() error
}
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(runtimeHost, codingagent.InteractiveModeOptions{
SessionHandle: sess, // *coding.Session implements this interface
...
})
type InteractiveThemeController ¶
type InteractiveThemeController struct {
// contains filtered or unexported fields
}
InteractiveThemeController consumes terminal reports on the owner loop. Dispose cancels and joins all admitted work.
func NewInteractiveThemeController ¶
func NewInteractiveThemeController(ctx context.Context, ui tui.TUI, options InteractiveThemeControllerOptions) (*InteractiveThemeController, error)
NewInteractiveThemeController resolves the initial theme on the owner loop, as theme-controller.ts's constructor calls initTheme.
func (*InteractiveThemeController) ApplyFromSettings ¶
func (controller *InteractiveThemeController) ApplyFromSettings(ctx context.Context) error
ApplyFromSettings applies the theme setting on the owner loop and starts the terminal color query without waiting for it. WaitForTerminalColors waits for the colors.
func (*InteractiveThemeController) ConsumeInput ¶
func (controller *InteractiveThemeController) ConsumeInput(data string) bool
ConsumeInput consumes terminal reports before viewport or focused-component input. Call it on the owner loop.
func (*InteractiveThemeController) DisableAutoSync ¶
func (controller *InteractiveThemeController) DisableAutoSync()
DisableAutoSync stops terminal color-scheme notifications on the owner loop.
func (*InteractiveThemeController) Dispose ¶
func (controller *InteractiveThemeController) Dispose() error
Dispose runs off-loop while the owner executor is alive. It releases query waiters and joins started work before returning.
type InteractiveThemeControllerOptions ¶
type InteractiveThemeControllerOptions struct {
GetSettingsManager func() *SettingsManager
ShowError func(string)
OnChanged func()
InitialThemeSetting *string
Output io.Writer
RunOnMain func(context.Context, func()) error
}
InteractiveThemeControllerOptions binds the shared theme state machine to a presentation owner and settings store. Callbacks run on the UI owner.
type InteractiveTuiOptions ¶
type InteractiveTuiOptions struct {
TuiMode string
ShowHardwareCursor *bool
LogDirectory string
Output io.Writer
// Terminal is the terminal the renderer drives (createInteractiveTui's `terminal`, tui-renderer.ts); nil selects the process terminal. Output, when set, takes precedence: it is the fixed-size paint surface of tests.
Terminal tui.Terminal
OnRightClickPaste func()
FullscreenCopyOnSelect *bool
// FullscreenWheelScrollLines is the fullscreen renderer's wheel line count; nil is auto (tui-renderer.ts:38).
FullscreenWheelScrollLines *tui.WheelScrollLines
OpenURL func(string) error
CopySelection func(string) error
}
InteractiveTuiOptions supplies the shared paint surface. The driver owns terminal input, dispatch and shutdown. Nil Output selects the process terminal; nil ShowHardwareCursor preserves the renderer's construction default.
type KeybindingConflict ¶
KeybindingConflict is upstream KeybindingConflict: a key claimed by more than one keybinding.
type KeybindingDefinition ¶
type KeybindingValue ¶
KeybindingValue is one entry of a keybindings config, `KeyId | KeyId[]` (tui keybindings.ts KeybindingsConfig): Key holds a single binding, Keys a list. JSON reads and writes the string or the array it was given.
func (KeybindingValue) MarshalJSON ¶
func (v KeybindingValue) MarshalJSON() ([]byte, error)
MarshalJSON writes the list when Keys is set and the single key otherwise.
func (*KeybindingValue) UnmarshalJSON ¶
func (v *KeybindingValue) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a string as the single key and an array as the list.
type KeybindingsManager ¶
type KeybindingsManager struct {
// contains filtered or unexported fields
}
func DefaultKeybindingsManager ¶
func DefaultKeybindingsManager() *KeybindingsManager
func NewKeybindingsManager ¶
func NewKeybindingsManager(agentDir string) *KeybindingsManager
NewKeybindingsManager is upstream KeybindingsManager.create(agentDir): it loads agentDir's keybindings.json. An empty agentDir is `new KeybindingsManager()`, which has no config file, so Reload keeps the current user bindings.
func NewKeybindingsManagerFromBindings ¶
func NewKeybindingsManagerFromBindings(userBindings map[string][]KeyID, configPath string) *KeybindingsManager
NewKeybindingsManagerFromBindings is upstream's `new KeybindingsManager(userBindings, configPath)` (keybindings.ts:374): the merged KEYBINDINGS table with the given user bindings, and the file Reload reads. An empty configPath has no file.
func (*KeybindingsManager) ExtensionKeybindingTable ¶
func (km *KeybindingsManager) ExtensionKeybindingTable() map[string]any
ExtensionKeybindingTable supplies the platform definitions and user overrides used by extension editor and UI factories. The definitions depend only on the platform, so every table of one platform shares them; the table is encoded for extensions and never modified.
func (*KeybindingsManager) GetConflicts ¶
func (km *KeybindingsManager) GetConflicts() []KeybindingConflict
GetConflicts is upstream getConflicts: the keys that more than one user binding claims, each with its own copy of the keybindings.
func (*KeybindingsManager) GetDefinition ¶
func (km *KeybindingsManager) GetDefinition(action string) (KeybindingDefinition, bool)
GetDefinition returns the definition of an action in the merged tui.* and app.* table for the manager's platform, and whether the table has one (keybindings.ts getDefinition over KEYBINDINGS).
func (*KeybindingsManager) GetEffectiveConfig ¶
func (km *KeybindingsManager) GetEffectiveConfig() map[string]KeybindingValue
GetEffectiveConfig returns every action's resolved binding as the keybindings config holds it: the key for a single binding, the list for several (keybindings.ts getEffectiveConfig, which is getResolvedBindings of the merged table).
func (*KeybindingsManager) GetKeys ¶
func (km *KeybindingsManager) GetKeys(action string) []KeyID
GetKeys is upstream getKeys: a copy of the keys resolved for a keybinding.
func (*KeybindingsManager) GetResolvedBindings ¶
func (km *KeybindingsManager) GetResolvedBindings() map[string][]string
GetResolvedBindings returns a detached snapshot of the resolved key IDs of every action of the merged table, tui.* and app.* alike (keybindings.ts getResolvedBindings; Pi lists one key as a string and several as an array, which the Go form always holds as a slice).
func (*KeybindingsManager) GetUserBindings ¶
func (km *KeybindingsManager) GetUserBindings() map[string][]KeyID
GetUserBindings returns a copy of the user's overrides (keybindings.ts getUserBindings).
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) KeybindingIDs ¶
func (km *KeybindingsManager) KeybindingIDs() []string
KeybindingIDs lists every keybinding id of KEYBINDINGS in declaration order.
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) MatchesSelectPage ¶
func (km *KeybindingsManager) MatchesSelectPage(input string) bool
MatchesSelectPage reports whether input is bound to tui.select.pageUp or tui.select.pageDown.
func (*KeybindingsManager) Reload ¶
func (km *KeybindingsManager) Reload()
Reload is upstream reload(): without a config file it does nothing; otherwise the file replaces the user bindings.
func (*KeybindingsManager) Resolve ¶
func (km *KeybindingsManager) Resolve(input string) string
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 = sessionentry.LabelEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type LatestPiRelease ¶
LatestPiRelease is the newest release a version check reports. PackageName and Note are nil when the source omits them or they are blank; each value is trimmed.
upstream: packages/coding-agent/src/utils/version-check.ts:8 (LatestPiRelease), filled as getLatestPiRelease (:51-87) fills it.
type LoadPromptTemplatesOptions ¶
type LoadPromptTemplatesOptions struct {
// Cwd is the working directory for project-local templates.
Cwd string
// AgentDir is the agent config directory for global templates.
AgentDir string
// PromptPaths are explicit prompt template paths (files or directories).
PromptPaths []string
// IncludeDefaults includes the default prompt directories.
IncludeDefaults bool
}
LoadPromptTemplatesOptions are upstream's LoadPromptTemplatesOptions.
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 the user and project prompt directories when the agent directory and the working directory are given, then the explicit paths, and keeps the first template of each name, reporting the others as collisions as the resource loader does (DedupePromptTemplates).
func LoadPromptTemplatesFromOptions ¶
func LoadPromptTemplatesFromOptions(options LoadPromptTemplatesOptions) LoadPromptTemplatesResult
LoadPromptTemplatesFromOptions loads prompt templates from the global `<agentDir>/prompts/` and project `<cwd>/<config dir>/prompts/` directories when IncludeDefaults is set, then from the explicit paths. Every template is returned, the same name more than once: collisions belong to the resource loader.
upstream: prompt-templates.ts:217-266 (loadPromptTemplates)
type LoadSkillsFromDirOptions ¶
LoadSkillsFromDirOptions selects one skill directory and its provenance source.
type LoadSkillsOptions ¶
type LoadSkillsOptions struct {
CWD string
AgentDir string
SkillPaths []string
IncludeDefaults bool
}
LoadSkillsOptions selects default and explicit skill paths in their precedence order.
type LoadSkillsResult ¶
type LoadSkillsResult struct {
Skills []*SkillDef
Diagnostics []extension.ResourceDiagnostic
}
LoadSkillsResult contains accepted skills and ordered validation/collision diagnostics.
func LoadSkills ¶
func LoadSkills(options LoadSkillsOptions) (LoadSkillsResult, error)
LoadSkills resolves explicit paths, loads defaults when requested, and keeps the first public name and physical file. Invalid path syntax returns an error; read/metadata failures and name collisions remain diagnostics.
func LoadSkillsFromDir ¶
func LoadSkillsFromDir(options LoadSkillsFromDirOptions) LoadSkillsResult
LoadSkillsFromDir scans direct root Markdown files and nested SKILL.md files. A directory's own SKILL.md takes precedence, and invalid declared skills retain diagnostics while ordinary documentation is ignored.
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 is a pointer because Pi keeps an authored empty string (no indent) and defaults only an absent value.
CodeBlockIndent *string `json:"codeBlockIndent,omitempty"`
Mermaid string `json:"mermaid,omitempty"`
// contains filtered or unexported fields
}
MarkdownSettings mirrors upstream MarkdownSettings. Mirrors upstream settings-manager.ts MarkdownSettings.
func (MarkdownSettings) MarshalJSON ¶
func (m MarkdownSettings) MarshalJSON() ([]byte, error)
MarshalJSON writes an authored null codeBlockIndent back as null.
func (*MarkdownSettings) UnmarshalJSON ¶
func (m *MarkdownSettings) UnmarshalJSON(data []byte) error
UnmarshalJSON keeps an authored null codeBlockIndent apart from an absent one.
type MermaidRenderingMode ¶
type MermaidRenderingMode string
MermaidRenderingMode is when Mermaid code blocks render as diagrams (settings-manager.ts:79).
const ( MermaidRenderingOff MermaidRenderingMode = "off" MermaidRenderingFinal MermaidRenderingMode = "final" MermaidRenderingStreaming MermaidRenderingMode = "streaming" )
type MessageEntry ¶
type MessageEntry = sessionentry.MessageEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func AsMessage ¶
func AsMessage(e SessionEntry) (MessageEntry, bool)
AsMessage is asMessage for the packages that read a Session's entries.
type MissingSessionCwdError ¶
type MissingSessionCwdError struct{ Issue SessionCwdIssue }
func (*MissingSessionCwdError) Error ¶
func (err *MissingSessionCwdError) Error() string
type ModelChangeEntry ¶
type ModelChangeEntry = sessionentry.ModelChangeEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type ModelCycleResult ¶
type ModelCycleResult struct {
Model *ai.Model
ThinkingLevel ai.ModelThinkingLevel
IsScoped bool
}
ModelCycleResult reports a model-cycle selection and its clamped thinking level.
type ModelDataSource ¶
type ModelDataSource struct {
Generated *ai.GeneratedModel
Model *ai.Model
}
ModelDataSource is one model of GetAllModelData before it is built. A plain bundled catalog's model is its catalog entry (Generated), whose ToModel is the model GetAllModelData lists; any other provider's model is that model (Model).
type ModelEntry ¶
type ModelEntry struct {
// Type is the registry model's `type` member. A built-in catalog model and a Radius baseline model carry "chat", as the
// catalog data spells it (model-catalog.ts flattenModelCatalog keeps it); a Radius gateway or extension model carries
// what its source wrote (radius-config.ts getRadiusModelsFromConfig and provider-composer.ts extensionModelFromDefinition
// spread it); a models.json model never has one (provider-composer.ts modelFromJson builds it member by member).
Type ai.ModelType
// CatalogRecord is the record the model's object comes from: the built-in catalog entry (ai.GeneratedModel.Record), or for a
// model an extension registered Pi's spread of its definition (ai.ExtensionModelRecord); empty for a models.json model. Pi's
// model object for it is that record, member order included.
CatalogRecord string
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
// SamplingParamsByThinkingLevel overrides SamplingParams for the effective Pi thinking level.
SamplingParamsByThinkingLevel ai.SamplingParamsByThinkingLevel
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.
func NativeModelEntry ¶
func NativeModelEntry(model *ai.Model) ModelEntry
NativeModelEntry lowers native model data to the configured backend representation without resolving credentials.
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(providerID ...string) []*ai.Model
Registry *ModelRegistry
ModelBuilder func(spec string) (*ai.Model, error)
SessionHandle InteractiveSessionHandle
// Classify is the Session runtime's classify; an extension's ctx.modelRegistry.classify reaches it. Nil answers an error result.
Classify func(context.Context, *ai.ClassifierModel, ai.ClassifierContext, ...ai.ModelsClassifierOptions) ai.ClassifierResult
// GenerateImages is the Session runtime's generateImages; an extension's ctx.modelRegistry.generateImages reaches it. Nil answers an error result.
GenerateImages func(context.Context, *ai.ImageModel, ai.ImagesContext, ...ai.ModelsImagesOptions) ai.AssistantImages
Transport ai.Transport
}
type ModelOperationBridge ¶
type ModelPriceSource ¶
ModelPriceSource returns cache-read dollars per million tokens, or zero for an unknown model. It is the Go projection of cache-stats.ts's pricing-only getModel dependency.
type ModelReferenceRequest ¶
type ModelReferenceRequest struct {
// Text is a bare model id or `provider/id`, optionally followed by `:<thinking>`.
Text string
// Provider restricts the lookup to one provider.
Provider string
ThinkingSuffix ThinkingSuffixMode
// Fuzzy matches id and name substrings when no exact match exists.
Fuzzy bool
}
ModelReferenceRequest mirrors upstream ModelReferenceRequest.
type ModelReferenceResult ¶
type ModelReferenceResult struct {
Status ModelReferenceStatus
Model *RuntimeModel
ThinkingLevel string
Warning string
Candidates []RuntimeModel
UsableCount int
Target *ModelReferenceTarget
}
ModelReferenceResult mirrors upstream ModelReferenceResult.
func ResolveModelReference ¶
func ResolveModelReference(request ModelReferenceRequest, models []RuntimeModel, usable func(provider string) bool) ModelReferenceResult
ResolveModelReference mirrors upstream resolveModelReference. usable only breaks ties between providers.
type ModelReferenceStatus ¶
type ModelReferenceStatus int
ModelReferenceStatus is the ModelReferenceResult.status discriminant.
const ( ModelReferenceNotFound ModelReferenceStatus = iota ModelReferenceResolved ModelReferenceAmbiguous )
type ModelReferenceTarget ¶
type ModelReferenceTarget struct {
Provider string
ProviderModels []RuntimeModel
ModelText string
ModelID string
ThinkingLevel string
}
ModelReferenceTarget mirrors upstream ModelReferenceTarget.
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 NewModelRegistryWithModelsPath ¶
func NewModelRegistryWithModelsPath(modelsPath string) *ModelRegistry
NewModelRegistryWithModelsPath loads the explicitly selected model configuration. An empty path disables the file. Ports packages/coding-agent/src/core/model-runtime.ts:176-184.
func (*ModelRegistry) AvailabilityReadContext ¶
func (r *ModelRegistry) AvailabilityReadContext(ctx context.Context) context.Context
AvailabilityReadContext gives a full availability pass one view of auth.json (readSnapshotContext) when no provider in it runs extension code. Pi's runAvailabilityRefresh makes every credential read before any I/O of the pass completes, so the pass stats once. An extension provider's check runs its own code between Pi's reads, so a pass with one reads as before, each read statting.
func (*ModelRegistry) AvailableProviderCount ¶
func (r *ModelRegistry) AvailableProviderCount() int
AvailableProviderCount returns the number of distinct providers with configured auth: Radius, dynamic, models.json and built-in providers, like the providers of getAvailable() that updateAvailableProviderCount counts (interactive-mode.ts:5252-5256). /sprite create uses it to require a configured provider.
func (*ModelRegistry) AwaitModelTasks ¶
func (r *ModelRegistry) AwaitModelTasks(ctx context.Context, tasks ...func(context.Context) error) error
AwaitModelTasks mirrors Promise.all: first rejection settles the waiter, success requires every task, and the task owner joins all remaining tasks without cancelling them on rejection.
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) CacheReadPrice ¶
func (r *ModelRegistry) CacheReadPrice(providerID, modelID string) float64
CacheReadPrice reads composed model pricing without resolving credentials, executing configuration commands, or performing network work.
func (*ModelRegistry) CheckRegistryAuth ¶
CheckRegistryAuth checks provider configuration without resolving command-backed fallback keys.
func (*ModelRegistry) CloseModelTasks ¶
func (r *ModelRegistry) CloseModelTasks()
CloseModelTasks stops admission, cancels the owner, and waits for admitted jobs and failed Promise siblings to drain. It then cancels the remote catalog collection's refreshes and waits for its operations, which are only this registry's catalog refreshes, so no store or credential read they started outlives Close. It also cancels the native Models collection's active refreshes, including a queued registration refresh's provider callbacks, without waiting for caller-owned Models operations such as in-flight streams or logins. Call it outside model callbacks.
func (*ModelRegistry) CompatibilityRequestHeaders ¶
func (r *ModelRegistry) CompatibilityRequestHeaders(model *ai.Model) (ai.ProviderHeaders, bool, error)
CompatibilityRequestHeaders resolves configured headers even when no API key is configured.
func (*ModelRegistry) ConfiguredRequestAuthStatus ¶
func (r *ModelRegistry) ConfiguredRequestAuthStatus(providerID string) (ai.AuthStatus, bool)
ConfiguredRequestAuthStatus reports explicit provider configuration without reading credentials or executing command values. Like Pi provider-composer.ts:597-610, a "$VAR" key is evaluated against the process environment, never a stored credential's env, so this synchronous snapshot getter performs no credential I/O.
func (*ModelRegistry) ExtensionProviderAuth ¶
func (r *ModelRegistry) ExtensionProviderAuth(ctx context.Context, providerID string) (*ai.AuthResult, error)
ExtensionProviderAuth mirrors upstream ModelRuntime.getAuth(provider): the provider's request auth, or nil when it has none.
func (*ModelRegistry) ExtensionProviderAuthStatus ¶
func (r *ModelRegistry) ExtensionProviderAuthStatus(providerID string) ai.AuthStatus
ExtensionProviderAuthStatus mirrors upstream ModelRuntime.getProviderAuthStatus: a runtime API key, then a stored credential, then the API key an extension registration or models.json configures, then the provider's ambient credentials.
func (*ModelRegistry) ExtensionRefresh ¶
func (r *ModelRegistry) ExtensionRefresh(ctx context.Context, allowNetwork *bool, providers []string, force *bool) CatalogRefreshResult
ExtensionRefresh mirrors upstream ModelRuntime.refresh: reload models.json, then refresh the provider catalogs, from the network only when allowed.
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. It omits the models of a stripped API, as the composed catalog does (ai.OfferedModels).
func (*ModelRegistry) GetAllModelData ¶
func (r *ModelRegistry) GetAllModelData() []*ai.Model
GetAllModelData returns the composed catalog in provider order without running credential configuration expressions.
func (*ModelRegistry) GetAllModelDataSources ¶
func (r *ModelRegistry) GetAllModelDataSources() []ModelDataSource
GetAllModelDataSources is GetAllModelData for a caller that reads every model's identity and builds few models: it lists the same models, in the same order, without building a plain bundled catalog's models.
func (*ModelRegistry) GetAllProviderModelData ¶
func (r *ModelRegistry) GetAllProviderModelData() []ai.AnyModel
GetAllProviderModelData lists the models of every type of every provider in provider order.
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) GetAvailableAllModelDataContext ¶
func (r *ModelRegistry) GetAvailableAllModelDataContext(ctx context.Context, providerID string) ([]ai.AnyModel, error)
GetAvailableAllModelDataContext lists the models of every type whose provider has working credentials, checking providers concurrently like GetAvailableModelDataContext. Chat models follow the provider's chat availability; every other model type is kept (models.ts getAllAvailable).
func (*ModelRegistry) GetAvailableModelData ¶
func (r *ModelRegistry) GetAvailableModelData() []*ai.Model
GetAvailableModelData returns the available catalog without request authentication or backend construction. It reads every provider's catalog as GetAllModelData does, in the same order, but builds a model of a plain bundled catalog (plainGeneratedModels) only when the model is available: a catalog built for a provider without auth is discarded unseen.
func (*ModelRegistry) GetAvailableModelDataContext ¶
func (r *ModelRegistry) GetAvailableModelDataContext(ctx context.Context, providerID string) ([]*ai.Model, error)
GetAvailableModelDataContext awaits provider auth and account filtering without resolving request-only credentials or constructing backend clients. The first rejection returns immediately while the shared owner drains other providers.
func (*ModelRegistry) GetCompatibilityRequestConfig ¶
func (r *ModelRegistry) GetCompatibilityRequestConfig(model *ai.Model) (CompatibilityRequestConfig, error)
GetCompatibilityRequestConfig resolves the configured request headers and the authHeader flag of a model. A header value that cannot be resolved is an error (resolveHeadersOrThrow).
func (*ModelRegistry) GetNativeModels ¶
func (r *ModelRegistry) GetNativeModels(id ...string) []*ai.Model
GetNativeModels returns provider-owned model data without building backend clients.
func (*ModelRegistry) GetProvider ¶
func (r *ModelRegistry) GetProvider(id string) *ai.ModelsProvider
GetProvider returns a native or composed provider by exact ID.
func (*ModelRegistry) GetProviderAllModelData ¶
func (r *ModelRegistry) GetProviderAllModelData(id string) []ai.AnyModel
GetProviderAllModelData lists the models of every type of one provider without resolving credentials.
func (*ModelRegistry) GetProviderAuth ¶
func (r *ModelRegistry) GetProviderAuth(ctx context.Context, id string) (*ai.AuthResult, error)
GetProviderAuth resolves native provider auth against the shared credential store.
func (*ModelRegistry) GetProviderAuthChecks ¶
func (r *ModelRegistry) GetProviderAuthChecks(ctx context.Context) (map[string]*ai.AuthCheck, error)
GetProviderAuthChecks starts every provider's current auth check, including empty catalogs. The first rejection returns immediately; Services retains and drains the remaining checks.
func (*ModelRegistry) GetProviderAuthStatus ¶
func (r *ModelRegistry) GetProviderAuthStatus(providerID string) ai.AuthStatus
func (*ModelRegistry) GetProviderDisplayName ¶
func (r *ModelRegistry) GetProviderDisplayName(providerID string) string
GetProviderDisplayName is the composed provider's name, or the ID (model-registry.ts getProviderDisplayName). The composer names a provider after its registration, then its models.json entry, then its base (provider-composer.ts composeModelProvider).
func (*ModelRegistry) GetProviderModelData ¶
func (r *ModelRegistry) GetProviderModelData(id string) []*ai.Model
GetProviderModelData composes metadata without resolving keys, headers, or backend clients. Like the catalog and the native collection it composes from, it omits the models of a stripped API, including models.json and extension definitions on one (ai.OfferedModels).
func (*ModelRegistry) GetProviderModelDataByID ¶
func (r *ModelRegistry) GetProviderModelDataByID(id, modelID string) *ai.Model
GetProviderModelDataByID is the first model of GetProviderModelData(id) whose ID is modelID, or nil. A plain bundled catalog is searched by entry and only the match is built, where GetProviderModelData builds every model of the provider (about 8 allocations and 1 KB each).
func (*ModelRegistry) GetRegisteredNativeProvider ¶
func (r *ModelRegistry) GetRegisteredNativeProvider(id string) *ai.ModelsProvider
GetRegisteredNativeProvider returns the caller's original native registration.
func (*ModelRegistry) GetRegisteredProviderConfig ¶
func (r *ModelRegistry) GetRegisteredProviderConfig(id string) *ProviderConfigInput
GetRegisteredProviderConfig returns the active core provider-registration input.
func (*ModelRegistry) GetRegisteredProviderIDs ¶
func (r *ModelRegistry) GetRegisteredProviderIDs() []string
GetRegisteredProviderIDs lists the IDs registered through RegisterProvider in registration order, then those registered as native providers in registration order (model-runtime.ts:518-520).
func (*ModelRegistry) GetTypedProvider ¶
func (r *ModelRegistry) GetTypedProvider(id string, fallback ai.ModelsStreamFunction) *ai.ModelsProvider
GetTypedProvider returns the composed provider with the given ID: a registered native or composed provider, else the built-in provider composed with models.json and legacy registrations, streaming through fallback. It returns nil for an unknown provider.
func (*ModelRegistry) GetTypedProviders ¶
func (r *ModelRegistry) GetTypedProviders(fallback func(id string) ai.ModelsStreamFunction) []*ai.ModelsProvider
GetTypedProviders lists every composed provider in provider order, each streaming through the fallback of its ID (models.ts getProviders). A provider that fails to compose is omitted.
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) HasRegisteredProvider ¶
func (r *ModelRegistry) HasRegisteredProvider(providerID string) bool
HasRegisteredProvider reports whether an extension owns an overlay for providerID.
func (*ModelRegistry) HoldRegistrationRefresh ¶
func (r *ModelRegistry) HoldRegistrationRefresh() (release func())
HoldRegistrationRefresh keeps StartRegistrationRefresh from starting the queued pass until the returned release function has run for every hold; the registrations only queue. A caller that loads several extension factories holds while it loads, as Pi queues their provider registrations and flushes them only after every factory has finished (agent-session-services.ts:158-182; the reload path's bindCore flush). An awaited yield ignores holds, because the awaiting caller has ended its turn. Releasing the last hold starts the queued pass. Release is idempotent.
func (*ModelRegistry) ListCredentials ¶
func (r *ModelRegistry) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
ListCredentials enumerates the runtime overlay and shared credential storage.
func (*ModelRegistry) LoadError ¶
func (r *ModelRegistry) LoadError() string
LoadError returns model configuration read, parse, and schema errors with the source path. Provider refresh failures surface through the Model Runtime's availability error, as in Pi.
func (*ModelRegistry) LoginNativeProvider ¶
func (r *ModelRegistry) LoginNativeProvider(ctx context.Context, id string, kind ai.AuthType, interaction ai.AuthInteraction, options ...ai.LoginOptions) (ai.Credential, error)
LoginNativeProvider serializes same-provider login and logout through persistence and local synchronization. It logs in the composed provider GetTypedProvider returns for the ID, a built-in or models.json provider included, and passes the optional LoginOptions to the provider's login. A synchronization failure returns the committed credential with CredentialSynchronizationError.
func (*ModelRegistry) LogoutNativeProvider ¶
func (r *ModelRegistry) LogoutNativeProvider(ctx context.Context, id string) error
LogoutNativeProvider serializes deletion and local synchronization with other credential operations for this provider. A synchronization failure reports that deletion committed.
func (*ModelRegistry) ModelProviderIDs ¶
func (r *ModelRegistry) ModelProviderIDs() []string
ModelProviderIDs lists the IDs of every provider something defines, in provider order: built-ins, then models.json, then registrations (model-runtime.ts providerIds). A provider with no composed form is still listed.
func (*ModelRegistry) ModelTaskContext ¶
func (r *ModelRegistry) ModelTaskContext(ctx context.Context) context.Context
ModelTaskContext links operation cancellation to the Services lifetime while preserving caller values and cancellation causes. It does not cancel a retained signal when an operation settles.
func (*ModelRegistry) NativeModels ¶
func (r *ModelRegistry) NativeModels() *ai.Models
NativeModels returns the provider-owned collection sharing this registry's credentials and ModelsStore.
func (*ModelRegistry) NativeProvider ¶
func (r *ModelRegistry) NativeProvider(id string) *extension.NativeProvider
func (*ModelRegistry) NativeProviderAuth ¶
func (r *ModelRegistry) NativeProviderAuth(ctx context.Context, id string, overrides ai.AuthResolutionOverrides) (*ai.AuthResult, error)
NativeProviderAuth resolves auth and commits a rotated credential atomically. The credential-store lock spans the reverse callback just as Pi's modify spans OAuth refresh. Missing credentials and callback failures never fall back.
func (*ModelRegistry) ObserveChanges ¶
func (r *ModelRegistry) ObserveChanges(notify func()) func()
ObserveChanges subscribes without replacing the host's catalog listener. Detach drains an in-flight callback and prevents later admission.
func (*ModelRegistry) ProviderInsecure ¶
func (r *ModelRegistry) ProviderInsecure(providerID string) bool
ProviderInsecure returns the configured transport flag without resolving credentials or headers.
func (*ModelRegistry) ProviderIsSubscription ¶
func (r *ModelRegistry) ProviderIsSubscription(providerID string) bool
ProviderIsSubscription reads the currently composed provider's OAuth capability without reading credentials.
func (*ModelRegistry) ProviderStreamSimple ¶
func (r *ModelRegistry) ProviderStreamSimple(name string, api ai.API) extension.ProviderStreamSimple
ProviderStreamSimple returns the custom stream callback owned by this registry's current provider registration when api is the api that registration declares. A model of that provider whose api differs reaches its API implementation instead (provider-composer.ts:590 `extension?.streamSimple && model.api === extension.api`). It never installs a global API handler.
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. Store reads and token refreshes honor ctx; storage failures are returned instead of falling through to ambient credentials.
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) ReadCredential ¶
func (r *ModelRegistry) ReadCredential(ctx context.Context, providerID string) (*ai.Credential, error)
ReadCredential reads a provider credential through the runtime overlay.
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) RefreshModelRuntime ¶
func (r *ModelRegistry) RefreshModelRuntime(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
RefreshModelRuntime reloads configuration and refreshes every selected provider through the registry's shared coordinator. A refresh over every provider first yields to the queued registration refresh, and a provider-scoped refresh covers the queued registrations of its own providers (model-runtime.ts:750,788,796).
func (*ModelRegistry) RefreshNativeProviders ¶
func (r *ModelRegistry) RefreshNativeProviders(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
RefreshNativeProviders awaits native catalog publication and the bound availability snapshot before returning to credential synchronization.
func (*ModelRegistry) RegisterExtensionProvider ¶
func (r *ModelRegistry) RegisterExtensionProvider(name string, configMap extension.ProviderConfig) error
RegisterExtensionProvider validates the incoming configuration before changing the registry. Legacy entry points merge without dropping omitted callbacks; a native registration is displaced only after validation succeeds. A stored or configured provider is provisionally available in the Services snapshot before observers run; its availability refresh is scheduled after them.
func (*ModelRegistry) RegisterNativeModelsProvider ¶
func (r *ModelRegistry) RegisterNativeModelsProvider(provider *ai.ModelsProvider) error
RegisterNativeModelsProvider replaces legacy registration state with the native catalog/auth/API callbacks, while retaining models.json overlays. It returns without authenticating or waiting for availability: the bound projection republishes the catalog, and the local refresh is queued for the caller's next yield.
func (*ModelRegistry) RegisterNativeProvider ¶
func (r *ModelRegistry) RegisterNativeProvider(ctx context.Context, p *extension.NativeProvider) error
RegisterNativeProvider installs the object and model snapshot and queues the local refresh, as Pi's registerNativeProvider does. It performs no authentication and calls no provider callback; both happen in the queued refresh. The bound availability projection runs before listeners are notified.
func (*ModelRegistry) RegisterProviderInput ¶
func (r *ModelRegistry) RegisterProviderInput(id string, input ProviderConfigInput, fallback ai.ModelsStreamFunction) error
RegisterProviderInput composes legacy model and OAuth callbacks over built-in/configured metadata. Both legacy entry points share merge state, while a prior native registration is replaced. A configured or stored-credential registration is provisionally available until its queued local refresh runs.
func (*ModelRegistry) RemoveRuntimeAPIKey ¶
func (r *ModelRegistry) RemoveRuntimeAPIKey(providerID string)
RemoveRuntimeAPIKey drops providerID's runtime key. Mirrors upstream ModelRuntime.removeRuntimeApiKey.
func (*ModelRegistry) RemoveRuntimeAPIKeyOperation ¶
func (r *ModelRegistry) RemoveRuntimeAPIKeyOperation(ctx context.Context, providerID string) error
RemoveRuntimeAPIKeyOperation drops the non-persistent key like RemoveRuntimeAPIKey, serialized with the other credential operations of the provider and followed by local synchronization (model-runtime.ts removeRuntimeApiKey).
func (*ModelRegistry) RequestAuthHeaders ¶
func (r *ModelRegistry) RequestAuthHeaders(model *ai.Model, headers ai.ProviderHeaders) ai.ProviderHeaders
RequestAuthHeaders folds configured HTTP header names in declaration order while compatibility auth results retain their original keys and null values.
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) ResolveCompatibilityModelAuth ¶
func (r *ModelRegistry) ResolveCompatibilityModelAuth(ctx context.Context, model *ai.Model) (*ai.AuthResult, error)
ResolveCompatibilityModelAuth returns request credentials or unconfigured compatibility headers, preserving nullable header suppression and the facade's error messages.
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) ResolveRegistryModelAuth ¶
func (r *ModelRegistry) ResolveRegistryModelAuth(ctx context.Context, model *ai.Model, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
ResolveRegistryModelAuth preserves nullable provider headers and resolves model headers after authentication.
func (*ModelRegistry) ResolveRegistryProviderAuth ¶
func (r *ModelRegistry) ResolveRegistryProviderAuth(ctx context.Context, id string, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
ResolveRegistryProviderAuth resolves provider credentials only at the request boundary.
func (*ModelRegistry) ResolveRegistryTypedModelAuth ¶
func (r *ModelRegistry) ResolveRegistryTypedModelAuth(ctx context.Context, model ai.AnyModel, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
ResolveRegistryTypedModelAuth resolves request auth for an image or classifier model: provider auth plus the model's own headers and the configured headers of its definition.
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 composed selection metadata without resolving request authentication or copying unused request capabilities.
func (*ModelRegistry) SetAPIStream ¶
func (r *ModelRegistry) SetAPIStream(fn func(id string) ai.ModelsStreamFunction)
SetAPIStream installs the API stream functions of composed registrations, Pi's getApiProvider(model.api) (provider-composer.ts:597-602).
func (*ModelRegistry) SetAuthStorage ¶
func (r *ModelRegistry) SetAuthStorage(auth *ai.AuthStorage)
SetAuthStorage wires the auth.json credential store for auth-aware filtering. A nil storage leaves the registry without stored credentials.
func (*ModelRegistry) SetAvailabilityRefresh ¶
func (r *ModelRegistry) SetAvailabilityRefresh(refresh func(context.Context, []string) ai.ModelsRefreshResult)
SetAvailabilityRefresh binds the Services-owned snapshot reconciler before the registry is shared with consumers. It runs after catalog publication and inside credential synchronization.
func (*ModelRegistry) SetAvailabilitySnapshot ¶
func (r *ModelRegistry) SetAvailabilitySnapshot(configured func(providerID string) bool, sync func(providerID string, provisional *ai.AuthCheck, providerOrder func() []string))
SetAvailabilitySnapshot binds the Services-owned availability snapshot before the registry is shared with consumers. configured reports configured auth for Models-collection providers. Registration and removal call sync with a reader of the catalog's provider order after the catalog commits and before change observers run. A nil provisional check grants no availability before the queued refresh. upstream: packages/coding-agent/src/core/model-runtime.ts:registerProvider
func (*ModelRegistry) SetCatalogBaseURL ¶
func (r *ModelRegistry) SetCatalogBaseURL(baseURL string)
SetCatalogBaseURL selects the remote catalog endpoint; empty selects DefaultCatalogBaseURL. upstream: model-runtime.ts:CreateModelRuntimeOptions.catalogBaseUrl
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) SetCredentialStore ¶
func (r *ModelRegistry) SetCredentialStore(store ai.CredentialStore)
SetCredentialStore wires the credential store for auth-aware filtering and resets the runtime-key overlay. Call it before using the registry.
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. Each republication projects availability and queues the local refresh.
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) SetRuntimeAPIKeyOperation ¶
func (r *ModelRegistry) SetRuntimeAPIKeyOperation(ctx context.Context, providerID, apiKey string) error
SetRuntimeAPIKeyOperation installs the non-persistent key like SetRuntimeAPIKey, serialized with the other credential operations of the provider and followed by local synchronization (model-runtime.ts setRuntimeApiKey). A synchronization failure returns CredentialSynchronizationError after the key is installed.
func (*ModelRegistry) StartModelTask ¶
StartModelTask admits background model work under the caller and Services lifetimes. False means the owner is closed or the context is nil. Work must report errors through its owning operation and must not close its own Services.
func (*ModelRegistry) StartRegistrationRefresh ¶
func (r *ModelRegistry) StartRegistrationRefresh(ctx context.Context)
StartRegistrationRefresh starts the queued registration refresh, unless a hold is active, and does not wait for it. A caller whose operation is scoped to some providers and does not itself refresh their catalogs uses it (availability of one provider, its auth check, its login): Pi launches the registration refresh unawaited (model-runtime.ts:750,788,796), and those calls select only their own providers, so they never wait for another provider's callbacks. Services.Close cancels and drains the pass. Ports packages/coding-agent/src/core/model-runtime.ts:registerNativeProvider,registerProvider,unregisterProvider.
func (*ModelRegistry) UnregisterProvider ¶
func (r *ModelRegistry) UnregisterProvider(name string)
UnregisterProvider removes a runtime registration, projects the remaining catalog into the Services snapshot, notifies observers, and queues the local refresh. Pi does this for every call, including a name with no registration. upstream: packages/coding-agent/src/core/model-runtime.ts:unregisterProvider
func (*ModelRegistry) YieldToRegistrationRefresh ¶
func (r *ModelRegistry) YieldToRegistrationRefresh(ctx context.Context)
YieldToRegistrationRefresh runs the queued registration refresh before the caller's own awaited operation, as Pi's earlier-queued continuation runs before a later one, and waits for it. Only a caller whose operation covers every provider waits: Pi's refresh over every provider awaits each provider's callbacks, so its caller would wait for the same ones. The caller stops waiting when ctx ends, and a caller whose ctx has already ended only starts the pass; the pass then continues under the Services lifetime, and Services.Close cancels and drains it. A caller that finds nothing queued returns at once, even while a pass runs, so a provider callback that calls back into the runtime cannot deadlock the pass. The pass itself never yields. Ports packages/coding-agent/src/core/model-runtime.ts:registerNativeProvider,registerProvider,unregisterProvider.
type ModelResolverRuntime ¶
type ModelResolverRuntime interface {
GetModels(providerID string) []RuntimeModel
HasConfiguredAuth(providerID string) bool
}
ModelResolverRuntime supplies the catalog and configured-auth observations used by CLI resolution. Selection does not resolve credentials or refresh the catalog.
type ModelScopeDiagnostic ¶
ModelScopeDiagnostic identifies a pattern that did not resolve cleanly.
type ModelScopeRuntime ¶
type ModelScopeRuntime interface {
GetAvailable(ctx context.Context) ([]RuntimeModel, error)
}
ModelScopeRuntime supplies the models a scope resolves against (upstream ModelRuntime.getAvailable).
type NavigateTreeOptions ¶
type NavigateTreeOptions 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). NavigateTreeOptions are AgentSession.navigateTree's options (agent-session.ts navigateTree): summarize, customInstructions, replaceInstructions and label.
type NavigateTreeResult ¶
type NavigateTreeResult struct {
}
type NewSessionOptions ¶
type NewSessionOptions = sessionentry.NewSessionOptions
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type OutputPad ¶
type OutputPad int
OutputPad is the horizontal chat output padding: upstream `0 | 1` (settings-manager.ts:1488).
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"`
Autoload *bool `json:"autoload,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:"-"`
// contains filtered or unexported fields
}
PackageSource mirrors upstream settings-manager.ts PackageSource. JSON accepts either a bare string source or an object with resource filters and optional autoload selection.
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 PathMetadata ¶
type PathMetadata struct {
Source string
Scope string
Origin string
BaseDir string
// PackageRoot is the directory of the npm, git or local-directory Package that supplied the resource; it is empty for a top-level resource and for a local source that is a single file.
PackageRoot string
// ChangelogPath is the changelog file of the Package that supplied the resource, or empty when it has none (package-manager.ts PathMetadata.changelogPath).
ChangelogPath string
}
PathMetadata is package-manager.ts PathMetadata: where a resolved resource came from. BaseDir and PackageRoot are the Package directory for an npm, git or local-directory Package resource; a single-file local source has its directory as BaseDir and no PackageRoot. Extension package warnings read the root through ExtensionPackageRoot.
func ExtensionDiscoveredPathMetadata ¶
func ExtensionDiscoveredPathMetadata(extensionPath string) PathMetadata
ExtensionDiscoveredPathMetadata is the metadata agent-session.ts buildExtensionResourcePaths gives a path an extension's resources_discover handler returned: source "extension:<name>", scope "temporary", origin "top-level", and the extension's directory as baseDir (none for a synthetic path).
func (PathMetadata) SourceInfo ¶
func (m PathMetadata) SourceInfo(path string) PiSourceInfo
SourceInfo is source-info.ts createSourceInfo.
type PersonalizeCatalog ¶
type PersonalizeCatalog func(catalog []ai.AnyModel, refresh ai.RefreshModelsContext) ([]ai.AnyModel, error)
PersonalizeCatalog replaces the catalog with a credential-specific model list. upstream: remote-catalog-provider.ts:PersonalizeCatalog
type PiSourceInfo ¶
type PiSourceInfo = extension.SourceInfo
PiSourceInfo is upstream's SourceInfo (source-info.ts) as it travels to extensions and RPC clients: where a tool, command, template or skill came from.
func CLISourceInfo ¶
func CLISourceInfo(path string) PiSourceInfo
CLISourceInfo is the SourceInfo upstream stamps on a resource named on the command line.
func CreateSyntheticSourceInfo ¶
func CreateSyntheticSourceInfo(path string, options SyntheticSourceInfoOptions) PiSourceInfo
CreateSyntheticSourceInfo is upstream's createSyntheticSourceInfo (source-info.ts:41): a SourceInfo for a resource without a file source, with scope "temporary" and origin "top-level" unless the options name others.
func DefaultSourceInfoForPath ¶
func DefaultSourceInfoForPath(cwd, agentDir, filePath string) PiSourceInfo
DefaultSourceInfoForPath is resource-loader.ts getDefaultSourceInfoForPath: a path under the agent or project resource directories is local to that scope, and any other path is temporary.
func PiSourceInfoValue ¶
func PiSourceInfoValue(value extension.SourceInfo) PiSourceInfo
PiSourceInfoValue is the wire value of an extension's SourceInfo: the value itself, or upstream's local temporary default when the source has no path.
type ProcessFileOptions ¶
type ProcessFileOptions struct {
AutoResizeImages *bool
}
ProcessFileOptions controls CLI attachment resizing. A nil AutoResizeImages uses the upstream default, true.
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, options ...ProcessFileOptions) (ProcessedCLIArgs, error)
ProcessCLIFileArguments expands CLI @file arguments into text and images. Text files decode as UTF-8 with U+FFFD for each ill-formed subpart, drop a leading BOM, and use <file name="/abs/path">\ncontent\n</file>\n, including the separator when content ends in a newline. Images carry conversion or dimension hints; processing failures become omission notes. AutoResizeImages defaults to true and can be disabled until the request model is selected.
type ProgramStatusReporter ¶
type ProgramStatusReporter struct {
// contains filtered or unexported fields
}
ProgramStatusReporter reports interactive-mode state to the terminal (OSC 7501): `working` during agent runs and compaction, `blocked` while a dialog waits for the user, then `done`, `error`, or `idle` once the run settles. Messages are limited to the session name, dialog titles, and the first line of errors; prompts and assistant output are never reported. It runs on the interactive owner loop.
func NewProgramStatusReporter ¶
func NewProgramStatusReporter(getTerminal func() tui.Terminal, getSessionName func() string) *ProgramStatusReporter
NewProgramStatusReporter returns a reporter that writes to getTerminal's terminal and names runs after getSessionName.
func (*ProgramStatusReporter) HandleEvent ¶
func (r *ProgramStatusReporter) HandleEvent(event agent.AgentEvent)
HandleEvent updates the status from a Session event.
func (*ProgramStatusReporter) Report ¶
func (r *ProgramStatusReporter) Report()
Report sends the current status unless it is the one last sent.
func (*ProgramStatusReporter) Resend ¶
func (r *ProgramStatusReporter) Resend()
Resend sends the current status to the terminal even if it is the one last sent, for a terminal that replaced the one it was sent to.
func (*ProgramStatusReporter) Reset ¶
func (r *ProgramStatusReporter) Reset()
Reset forgets the previous session's run, for example after switching sessions.
func (*ProgramStatusReporter) SetBlocked ¶
func (r *ProgramStatusReporter) SetBlocked(source string, status *BlockedStatus)
SetBlocked reports `blocked` for a dialog until it is cleared with a nil status. Reopening a source replaces it.
type ProjectTrustDecision ¶
type ProjectTrustDecision = *bool
ProjectTrustDecision is a saved project trust decision: true trusts, false distrusts, nil is undecided (trust-manager.ts:9, boolean | null).
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) (ProjectTrustDecision, 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 ProjectTrustDecision) 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 = sessionentry.ProjectedSessionEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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" | "extra"
// SourceInfo is prompt-templates.ts PromptTemplate.sourceInfo, set by a resource loader from the resolved resource's metadata.
SourceInfo PiSourceInfo
}
PromptTemplate is one loaded `.md` file.
func DedupePromptTemplates ¶
func DedupePromptTemplates(templates []PromptTemplate) ([]PromptTemplate, []extension.ResourceDiagnostic)
DedupePromptTemplates keeps the first template of each name, in order, and reports each later one as a collision with the first.
Ports packages/coding-agent/src/core/resource-loader.ts (dedupePrompts). upstream: resource-loader.ts:1156-1181 (dedupePrompts)
type ProviderConfigInput ¶
type ProviderConfigInput = extension.ProviderConfigInput
ProviderConfigInput is the core registration input (provider-composer.ts:91 ProviderConfigInput).
func GraphProviderInput ¶
func GraphProviderInput(id string, raw json.RawMessage) (ProviderConfigInput, error)
GraphProviderInput is the ProviderConfigInput of the declarative ProviderConfig JSON an extension passed to registerProvider.
type ProviderRetryConfig ¶
type ProviderRetryConfig struct {
// TimeoutMs and MaxRetries are nil when unset, as upstream's `timeoutMs?` and `maxRetries?` are undefined; an explicit 0 is a pointer to 0.
TimeoutMs *int
MaxRetries *int
MaxRetryDelayMs int
}
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 QuietStartup ¶
type QuietStartup uint8
QuietStartup mirrors upstream QuietStartup (settings-manager.ts:111-112), the union boolean | "header": true hides all startup output, "header" keeps only the startup header.
const ( // QuietStartupFalse is false: the startup header and details show. It is the default. QuietStartupFalse QuietStartup = iota // QuietStartupTrue is true: the startup header and details are hidden. QuietStartupTrue // QuietStartupHeader is "header": the startup header shows and the details are hidden. QuietStartupHeader )
func (QuietStartup) MarshalJSON ¶
func (q QuietStartup) MarshalJSON() ([]byte, error)
MarshalJSON writes the upstream JSON value: false, true or "header".
func (QuietStartup) String ¶
func (q QuietStartup) String() string
String returns the value as upstream's String(quietStartup) spells it: "false", "true" or "header".
func (*QuietStartup) UnmarshalJSON ¶
func (q *QuietStartup) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a settings value as upstream getQuietStartup does (settings-manager.ts:1089-1092): true and "header" keep their meaning and every other value is false.
type RawEntry ¶
type RawEntry = sessionentry.RawEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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 warnings]`, `[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
// SystemPromptSourcePaths are the system prompt files the loaded
// resources [Context] section lists before ContextFiles.
SystemPromptSourcePaths []string
ResourceSourceInfo map[string]ResourceSourceInfo
// Err is the error resource resolution threw (an invalid settings file:
// URL); /reload fails with it and applies nothing.
Err error
}
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.
func (*RequestAuthRuntime) SynchronizeCredentialState ¶
func (r *RequestAuthRuntime) SynchronizeCredentialState(ctx context.Context, providerID string, operation CredentialSynchronizationOperation, credential *ai.Credential) error
SynchronizeCredentialState checks one provider after its credential changed, as upstream ModelRuntime.synchronizeCredentialState does: its composition, then its availability (credential read and auth check). A failure returns a *CredentialSynchronizationError: the credential change is already committed. A provider's composition depends on models.json and the built-in and Radius providers, which a credential change does not alter, so the composition from construction is what upstream's recomposeProvider rebuilds; reading it leaves the provider maps that off-loop auth checks read unchanged. The availability check covers only providerID, as upstream refreshProviderAvailability does.
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 ResolveCliModelResult ¶
type ResolveCliModelResult struct {
Model *RuntimeModel
ThinkingLevel ai.ThinkingLevel
Warning string
Error string
}
ResolveCliModelResult carries a model selection, optional thinking suffix, warning, or CLI diagnostic.
func ResolveCliModel ¶
func ResolveCliModel(cliProvider, cliModel, cliThinking string, inlineApiKey bool, runtime ModelResolverRuntime) ResolveCliModelResult
ResolveCliModel resolves explicit provider/model selections against all catalog models, not only available models. It parses a thinking suffix without applying it to a Session. inlineApiKey is --api-key supplied for the selected provider.
type ResolveModelScopeResult ¶
type ResolveModelScopeResult struct {
ScopedModels []ScopedModel
Diagnostics []ModelScopeDiagnostic
}
ResolveModelScopeResult preserves pattern order, first-occurrence model order, and diagnostics.
func ResolveModelScopeFromModels ¶
func ResolveModelScopeFromModels(patterns []string, models []RuntimeModel) ResolveModelScopeResult
ResolveModelScopeFromModels resolves a scope without refreshing or reading authentication.
func ResolveModelScopeWithDiagnostics ¶
func ResolveModelScopeWithDiagnostics(ctx context.Context, patterns []string, runtime ModelScopeRuntime) (ResolveModelScopeResult, error)
ResolveModelScopeWithDiagnostics resolves patterns against the runtime's available models and returns the diagnostics with the scope. A GetAvailable failure is returned unchanged, as upstream's awaited getAvailable rejects (model-resolver.ts resolveModelScopeWithDiagnostics).
type ResolvedPath ¶
ResolvedPath pairs a candidate input path with its canonical path. Returned by DedupBySymlink.
func DedupBySymlink ¶
func DedupBySymlink(paths []string) []ResolvedPath
DedupBySymlink returns the first input for each distinct canonical path, in input order. It follows symlinks and drive junctions but preserves Windows volume mount points as directories, as Node's realpathSync does. On resolution failure it keeps the raw path as its own canonical identity. Ports packages/coding-agent/src/core/package-manager.ts.
type ResolvedResource ¶
type ResolvedResource struct {
Path string
// Enabled is false for a resource that a filter or override disabled; its metadata still applies to the path.
Enabled bool
Metadata PathMetadata
}
ResolvedResource is a resolved resource path with its PathMetadata (package-manager.ts ResolvedResource).
func AmbientExtensionResources ¶
func AmbientExtensionResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
AmbientExtensionResources lists the extensions that settings and auto-discovery yield: project entries and auto-discovery, then user entries and auto-discovery, each with the PathMetadata package-manager.ts records. The project half is skipped when project is false.
func AmbientPromptResources ¶
func AmbientPromptResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
AmbientPromptResources lists the prompt templates that settings and auto-discovery yield: project entries and auto-discovery, then user entries and auto-discovery, each with the PathMetadata package-manager.ts records. The project half is skipped when project is false.
func AmbientSkillResources ¶
func AmbientSkillResources(cwd, agentDir string, sm *SettingsManager, project, user bool) []ResolvedResource
AmbientSkillResources lists the skills that settings and auto-discovery yield, in resourcePrecedenceRank order: project settings entries, project auto-discovery, ancestor .agents/skills, user settings entries, user auto-discovery, then ~/.agents/skills, each with the PathMetadata addAutoDiscoveredResources and resolveLocalEntries record and with the enabled state the settings' patterns give it; a disabled resource is listed, not dropped (package-manager.ts:188-195, 2329-2350, 2352-2495). The project half is skipped when project is false, as project trust does upstream.
func AmbientSkillResourcesIn ¶
func AmbientSkillResourcesIn(scan *AgentsSkillScan, cwd, agentDir string, sm *SettingsManager, project, user bool) []ResolvedResource
AmbientSkillResourcesIn is AmbientSkillResources with the ancestor .agents/skills directories of scan, which must be of cwd.
func AmbientThemeResources ¶
func AmbientThemeResources(cwd, agentDir string, sm *SettingsManager, project bool) []ResolvedResource
AmbientThemeResources lists the themes that settings and auto-discovery yield: project entries and auto-discovery, then user entries and auto-discovery, each with the PathMetadata package-manager.ts records. The project half is skipped when project is false.
func OrderResolvedResources ¶
func OrderResolvedResources(packages, ambient []ResolvedResource) []ResolvedResource
OrderResolvedResources is DefaultPackageManager.resolve's result for one resource type: the Packages' resources, then the settings entries (project, then user), then the auto-discovered resources fill a first-wins accumulator keyed by path, which keeps the earliest source's metadata and enabled state for a path several reach; the accumulator is stably sorted by resourcePrecedenceRank and reduced to the first resource of each canonical path (package-manager.ts:927-961, 2555-2565, 2576-2594). ambient is in AmbientSkillResources or AmbientPromptResources order.
func SkillEntryResources ¶
func SkillEntryResources(resources []ResolvedResource) []ResolvedResource
SkillEntryResources names each skill directory resource by its SKILL.md file, as Pi's collectSkillEntries does for settings entries, auto-discovery and Package manifests (package-manager.ts:365-400, 645-653, 2317-2327, 2518-2535). PiG's resource lists name the directory; Pi's accumulator and metadataByPath key the skill by the file, so a settings entry naming the file and one naming the directory reach the same resource.
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
// ChangelogPath is the changelog file of the package that supplied the resource, or "" (package-manager.ts PathMetadata.changelogPath).
ChangelogPath string
}
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. Ports packages/coding-agent/src/core/source-info.ts
func ExtensionDiscoveredSourceInfo ¶
func ExtensionDiscoveredSourceInfo(path, kind, extensionPath string) ResourceSourceInfo
ExtensionDiscoveredSourceInfo is the provenance upstream buildExtensionResourcePaths records for a resource path an extension's resources_discover handler returned: source "extension:<name>", scope "temporary", and the extension's directory as baseDir.
func (ResourceSourceInfo) DisplayName ¶
func (i ResourceSourceInfo) DisplayName() string
DisplayName derives the path-based resource name used for collision grouping. A skill entry file uses its parent directory, matching Pi's default skill name.
type RetryConfig ¶
type RetryConfig struct {
Enabled bool
MaxRetries int
BaseDelayMs int
// MaxAgentDelayMs is upstream's maxAgentDelayMs, the cap for exponential retry backoff.
MaxAgentDelayMs int
}
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 RoutedModelSelection ¶
type RoutedModelSelection struct {
Model *ai.Model
ThinkingLevel ai.ModelThinkingLevel
}
RoutedModelSelection is the physical model and thinking level a virtual model selection currently resolves to (AgentSession.routedModel).
type RuntimeModel ¶
type RuntimeModel struct {
// NativeModel retains the source model for native selection; it is not part of serialized metadata.
NativeModel *ai.Model `json:"-"`
Provider string
ID string
Name string
Reasoning bool
// Headers are the model's intrinsic catalog headers.
Headers ai.ProviderHeaders
// BuildNativeModel, set when NativeModel is nil, builds the source model; a list of many models that keeps few builds only those.
BuildNativeModel func() *ai.Model `json:"-"`
}
RuntimeModel carries the model identity, reasoning flag, and intrinsic headers used by request-auth and CLI resolution.
func FindExactModelReferenceMatch ¶
func FindExactModelReferenceMatch(modelReference string, models []RuntimeModel) *RuntimeModel
FindExactModelReferenceMatch mirrors upstream findExactModelReferenceMatch.
func (*RuntimeModel) SourceModel ¶
func (m *RuntimeModel) SourceModel() *ai.Model
SourceModel returns NativeModel, building it with BuildNativeModel first when it has not been built.
type RuntimeProvider ¶
type RuntimeProvider struct {
ID string
Name string
Auth ai.ProviderAuth
// contains filtered or unexported fields
}
RuntimeProvider carries the composed provider's identity, display name, auth methods, and model catalog.
type ScopedModel ¶
type ScopedModel struct {
Model RuntimeModel
ThinkingLevel string
}
ScopedModel pairs a model with an explicitly selected thinking level, if any.
func ResolveModelScope ¶
func ResolveModelScope(ctx context.Context, patterns []string, runtime ModelScopeRuntime) ([]ScopedModel, error)
ResolveModelScope is ResolveModelScopeWithDiagnostics that writes each diagnostic to stderr as a yellow "Warning: " line and returns only the scope (model-resolver.ts:372-382 resolveModelScope, console.warn(chalk.yellow(...))).
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 proven package-manager installation runs to update itself.
Mirrors upstream SelfUpdateCommand (config.ts). Steps holds an optional sequence of sub-commands (e.g. uninstall old name, then install new name).
func MakeConfiguredSelfUpdateCommand ¶
func MakeConfiguredSelfUpdateCommand(argv []string, release SelfUpdateRelease) *SelfUpdateCommand
MakeConfiguredSelfUpdateCommand fills the {packageName}, {version} and {installSpec} placeholders of a configured self-update command from release. Any other brace text stays as written.
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
// PackageDir is the owning package directory, not copied metadata below dist or a launcher directory.
PackageDir string
// NpmPrefix is retained only from a proven lib/node_modules root.
NpmPrefix 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. Explicit npm probe failures surface unless another proven owner selects the route.
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.
func (*SelfUpdateProvenance) GetSelfUpdateCommand ¶
func (p *SelfUpdateProvenance) GetSelfUpdateCommand(npmCommand []string, target SelfUpdatePackageTarget) *SelfUpdateCommand
GetSelfUpdateCommand builds a command only for the proven package-manager owner. An unconfigured npm command retains the prefix of its proven lib/node_modules root.
func (*SelfUpdateProvenance) GetSelfUpdateUnavailableInstruction ¶
func (p *SelfUpdateProvenance) GetSelfUpdateUnavailableInstruction() string
GetSelfUpdateUnavailableInstruction reports a concrete native ownership or permission failure instead of inventing an unproven package-manager command.
type SelfUpdateRelease ¶
SelfUpdateRelease is the release a configured self-update command installs.
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 NewBranchSession ¶
func NewBranchSession(header SessionHeader, branch []SessionEntry) *Session
NewBranchSession returns an in-memory session that holds header's identity and the entries of branch, root first, as they are: each entry keeps its id and parent link, and the session shares the entry values with the session they came from instead of encoding and decoding each record again, as agent-session.ts _createBoundaryPreviewManager hands SessionManager.inMemory the branch's own objects. The session serves reads of the branch's projection and further appends (a boundary preview appends its drafts). It keeps no statistics or name of the entries, which only a session that is saved or listed reads.
func NewSession ¶
NewSession creates an in-memory session with an ISO millisecond header timestamp and an optional parent session path.
func (*Session) Accounting ¶
func (s *Session) Accounting() SessionAccounting
func (*Session) AppendBashExecution ¶
func (s *Session) AppendBashExecution(message BashExecutionMessage) (string, error)
AppendBashExecution persists a completed user bash message, retaining the timestamp captured before any deferred append. Returns the new entry id (the new leaf).
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) AppendCompactionHookUndefined ¶
func (s *Session) AppendCompactionHookUndefined(summary, firstKeptEntryID string, tokensBefore int, details any, usage *ai.Usage) (string, error)
AppendCompactionHookUndefined is AppendCompaction for a caller that leaves fromHook undefined, as an extension's SessionManager.appendCompaction may: the entry then has no fromHook member.
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) AppendCustomEntry ¶
AppendCustomEntry records extension-owned data with a collision-checked ID on the active branch.
func (*Session) AppendCustomMessageEntry ¶
func (s *Session) AppendCustomMessageEntry(customType string, content any, display bool, details any) (string, error)
AppendCustomMessageEntry persists an extension-injected custom message as a "custom_message" entry and returns the new entry id.
func (*Session) AppendEntry ¶
AppendEntry appends a complete entry to memory and the session file. The caller supplies id, parentId and timestamp; a nil parent denotes a root and is never inferred from the current leaf. Returns an error if marshalling, parsing, or file write fails. Persistence errors expose Node's filesystem message while retaining the underlying Go error for errors.Is and errors.As.
func (*Session) AppendLabelChange ¶
AppendLabelChange writes a label entry for targetID and returns its id. label=nil clears any existing label. Mirrors upstream appendLabelChange in session-manager.ts.
func (*Session) AppendMessage ¶
func (s *Session) AppendMessage(message SessionMessage) (string, error)
AppendMessage persists one message (an agent.AgentMessage or a BashExecutionMessage), generating a fresh entry id and timestamp and linking it to the current leaf (session-manager.ts appendMessage). Any other SessionMessage is an error.
func (*Session) AppendModelChange ¶
AppendModelChange appends a model_change entry as a child of the current leaf, advances the leaf, and returns the entry id (session-manager.ts appendModelChange(provider, modelId)).
func (*Session) AppendSessionInfo ¶
AppendSessionInfo records a sanitized name change with a collision-checked ID on the active branch.
func (*Session) AppendSessionInfoName ¶
AppendSessionInfoName is AppendSessionInfo that also returns the name GetSessionName reports for the appended entry. Concurrent appends cannot change the returned name, so a caller publishes the name its own entry set.
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. It returns the new entry's id.
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 ¶
Branch 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 "branch before first entry" case (root-reset).
func (*Session) BranchWithSummary ¶
func (s *Session) BranchWithSummary(parentID *string, summary string, details any, fromHook bool, usage *ai.Usage) (string, error)
BranchWithSummary 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) 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) BuildContextEntries ¶
func (s *Session) BuildContextEntries() []SessionEntry
BuildContextEntries returns the compaction-aware entry list of the branch ending at the current leaf (session-manager.ts buildContextEntries). An unset leaf yields no entries.
func (*Session) BuildSessionContext ¶
func (s *Session) BuildSessionContext() SessionContext
BuildSessionContext returns the messages, thinking level and model of the branch ending at the current leaf (session-manager.ts buildSessionContext). An unset leaf 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) BuildSessionProjectionCalls ¶
BuildSessionProjectionCalls returns how many times BuildSessionProjection ran, the count upstream's test reads with vi.spyOn(sessionManager, "buildSessionProjection").
func (*Session) BuildSessionProjectionView ¶
func (s *Session) BuildSessionProjectionView() SessionProjection
BuildSessionProjectionView is BuildSessionProjection with the entries' own messages in place of copies. The caller reads them and never modifies them or hands them to code that might: an estimate over a long conversation then costs a walk of the branch and not a deep copy of every message in it. The projection of the current leaf is kept and extended by the entries appended to it, so a turn projects only its own entries; a leaf move, a compaction or a context edit projects the branch again. Entries are immutable once appended, so the result equals a new projection of the branch.
func (*Session) CheckSavedForFork ¶
CheckSavedForFork rejects a file-backed Session that has not been saved yet: no user or assistant message has created its file. In-memory Sessions do not require a file. Ports packages/coding-agent/src/core/agent-session-runtime.ts (fork).
func (*Session) CountEntriesOfType ¶
CountEntriesOfType returns how many entries of the log have the given type, without reading their bodies.
func (*Session) CreateBranchedSession ¶
CreateBranchedSession replaces this manager's active log with a new branch while retaining the manager object. A memory-only manager does not acquire a persistence path.
func (*Session) EntryReads ¶
EntryReads is how many entries the Session has read back from its records and decoded since it opened (a resident entry costs none). A test or diagnostic that bounds what a path reads compares it before and after the path.
func (*Session) ExportHeader ¶
func (s *Session) ExportHeader() SessionHeader
ExportHeader is the header serializeSessionBranch writes: the session's own id with the manager's resolved cwd (sessionManager.getCwd()), which differs from the stored header's cwd when that was spelled relative, with a `..` segment, or without a drive on Windows. upstream: packages/coding-agent/src/core/session-export.ts:serializeSessionBranch
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) GetBranch ¶
func (s *Session) GetBranch(fromID ...string) []SessionEntry
GetBranch returns the root-to-leaf path (root first) of the current leaf, or of fromID when it is given; nil when the entry does not exist. Mirrors upstream SessionManager.getBranch(fromId?).
func (*Session) GetBranchSystemMessages ¶
func (s *Session) GetBranchSystemMessages() []agent.AgentMessage
GetBranchSystemMessages returns the system messages of the branch ending at the current leaf, in branch order: the messages of the entries GetBranch returns whose message is a system message, read without reading or decoding any other entry. Pi's _restoreToolsFromTranscript (agent-session.ts:1815-1844) filters getBranch() the same way, where every entry is already decoded; here a branch of 90,000 entries would be read and decoded whole for the few system messages it holds.
pig additive (D112): the split between resident and file-backed entries is a Go memory choice; the result is Pi's.
func (*Session) GetChildren ¶
func (s *Session) GetChildren(parentID string) []SessionEntry
GetChildren returns the direct children of an entry in append order (session-manager.ts getChildren).
func (*Session) GetContextBranch ¶
func (s *Session) GetContextBranch() []SessionEntry
GetContextBranch returns the branch ending at the current leaf as the projection-level reads see it: every entry from the start of the latest compaction's kept range, every earlier entry that is not a message, and before the kept range the newest assistant message of each API. buildSessionProjection, getSessionContextSettings, prepareCompaction, the newest assistant usage and the newest compaction or model selection read the same from it as from GetBranch, without reading history the context no longer holds. Nil when there is no leaf.
func (*Session) GetEntries ¶
func (s *Session) GetEntries() []SessionEntry
GetEntries returns a copy of all session entries (in append order).
func (*Session) GetEntry ¶
func (s *Session) GetEntry(id string) (SessionEntry, bool)
GetEntry 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) GetEntryCount ¶
GetEntryCount returns the number of distinct session entry IDs, excluding the header, without copying entries like GetEntries. A loaded file that repeats an ID counts it once. Mirrors upstream getEntryCount, which returns byId.size (session-manager.ts:1511-1513).
func (*Session) GetHeader ¶
func (s *Session) GetHeader() SessionHeader
func (*Session) GetLabel ¶
GetLabel returns the label most recently set on an entry; a later empty or nil label clears it (session-manager.ts getLabel).
func (*Session) GetLeafEntry ¶
func (s *Session) GetLeafEntry() (SessionEntry, bool)
GetLeafEntry returns the entry at the current leaf, or false when there is none (session-manager.ts getLeafEntry).
func (*Session) GetLeafID ¶
GetLeafID 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) GetMessageEntriesWithRole ¶
func (s *Session) GetMessageEntriesWithRole(role string) []SessionEntry
GetMessageEntriesWithRole returns the message entries whose message.role is role, in append order, reading only those entries.
func (*Session) GetSessionDir ¶
GetSessionDir returns the configured session directory. A directly loaded log without an override uses its file's parent; an in-memory manager has no directory.
func (*Session) GetSessionFile ¶
GetSessionFile returns the selected persistence path, or nil for an in-memory manager. A selected file need not have been flushed yet.
func (*Session) GetSessionId ¶
GetSessionId returns the current log identity.
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) GetTree ¶
func (s *Session) GetTree() []*SessionTreeNode
GetTree builds the session's tree and returns its roots (session-manager.ts getTree): an entry without a parent, one that is its own parent and an orphan whose parent is missing are roots, in entry order. Children are sorted oldest first by timestamp (a stable sort, so an unparsable timestamp keeps its place); the roots are not sorted. A label resolves from the latest label entry for its target.
func (*Session) IsPersisted ¶
IsPersisted reports whether the manager has a persistence path, independently of the first assistant-triggered flush.
func (*Session) KeptRangeOnBranch ¶
KeptRangeOnBranch reports whether the current branch has no compaction, or its latest compaction's first kept entry lies before it on the branch: then the branch from the kept entry on is the same in GetContextBranch as in GetBranch.
func (*Session) NewSession ¶
func (s *Session) NewSession(options *NewSessionOptions) (string, error)
NewSession resets this manager to an empty Session with the same persistence mode and directory, and returns the new session file path (empty when the session is not persisted). An ID that is not a valid session id is an error and leaves the manager unchanged. Mirrors upstream SessionManager.newSession (core/session-manager.ts:1057).
func (*Session) ParentSession ¶
func (*Session) Persist ¶
func (s *Session) Persist(entry SessionEntry) error
Persist writes one entry the manager already holds to the session file, as upstream SessionManager._persist does (session-manager.ts:1172). An unflushed session is not written until it holds a user or assistant message, so setup entries alone leave no file. The first write creates the file with the header and every buffered entry; later calls append the entry. A session without a file persists nothing.
func (*Session) RawEntriesPage ¶
func (s *Session) RawEntriesPage(cursor, maxBytes int) (page []json.RawMessage, next, total int)
RawEntriesPage returns the records of the entries from cursor on whose lines (with their newline) fit in maxBytes, at least one, the cursor after them and the number of entries (a nil page at the end); a cursor out of range starts at 0. Records of entries that are not resident are read without decoding. A record with no JSON is skipped but counted.
func (*Session) ResetLeaf ¶
func (s *Session) ResetLeaf()
ResetLeaf moves the leaf before the first entry, so the next append creates a root (session-manager.ts resetLeaf).
func (*Session) Revision ¶
Revision identifies the current entries and leaf: it changes whenever either changes, so a value derived from the branch stays valid while the revision does.
func (*Session) SetCacheReadPriceSource ¶
func (s *Session) SetCacheReadPriceSource(prices ModelPriceSource)
SetCacheReadPriceSource binds runtime model prices during Session initialization or replacement. It rebuilds cache accounting only when historical misses need repricing; ordinary footer reads remain history-independent.
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) SetSessionFile ¶
SetSessionFile switches this manager to the session file at path, as upstream SessionManager.setSessionFile does for resume and branching. The manager keeps its cwd and session directory. A file with entries is loaded as flushed; an empty file starts a new session that a persisting manager writes as a header; a missing path starts a new session that keeps the explicit path until its first user or assistant message. Upstream assigns the session file before it reads the file, so a non-empty file that is not a session is an error after which a persisting manager writes to that path while its entries stay unchanged. A manager that does not persist reads the file but never writes it and keeps no session file. Mirrors upstream SessionManager.setSessionFile and _setSessionFile (core/session-manager.ts:1025-1054).
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.
func (*Session) UsesDefaultSessionDir ¶
UsesDefaultSessionDir reports whether the session directory is the default one for the session's working directory (session-manager.ts usesDefaultSessionDir). An in-memory manager has no session directory.
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 SessionContext ¶
type SessionContext = sessionentry.SessionContext
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func BuildSessionContext ¶
func BuildSessionContext(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) SessionContext
Ports packages/coding-agent/src/core/session-manager.ts (buildSessionContext). BuildSessionContext defaults to the last entry, falls back there for an unknown leaf, and treats an explicitly nil leaf as an empty branch. It returns the messages and settings of BuildSessionProjection, as session-manager.ts buildSessionContext does.
type SessionContextModel ¶
type SessionContextModel = sessionentry.SessionContextModel
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func GetSessionContextSettings ¶
func GetSessionContextSettings(path []SessionEntry) (thinkingLevel string, model *SessionContextModel)
GetSessionContextSettings returns the latest model and thinking settings on a root-to-leaf path without projecting or decoding message bodies. It mirrors session-manager.ts getSessionContextSettings.
type SessionCwdIssue ¶
type SessionCwdIssue struct {
SessionFile string `json:"sessionFile,omitempty"`
SessionCwd string `json:"sessionCwd"`
FallbackCwd string `json:"fallbackCwd"`
}
Ports packages/coding-agent/src/core/session-cwd.ts. SessionCwdIssue identifies a persisted Session whose effective working directory is missing.
func GetMissingSessionCwdIssue ¶
func GetMissingSessionCwdIssue(session *Session, fallbackCwd string) *SessionCwdIssue
type SessionEntry ¶
type SessionEntry = sessionentry.SessionEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func BugReportBranch ¶
func BugReportBranch(session *Session) []SessionEntry
BugReportBranch returns the entries on the current branch.
func BuildContextEntries ¶
func BuildContextEntries(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) []SessionEntry
BuildContextEntries returns the selected branch's compaction-aware entry list, including state-only entries.
type SessionEntryBase ¶
type SessionEntryBase = sessionentry.SessionEntryBase
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type SessionHeader ¶
type SessionHeader = sessionentry.SessionHeader
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func ReadSessionHeader ¶
func ReadSessionHeader(path string) (*SessionHeader, error)
ReadSessionHeader scans at most Pi's header-discovery bound. Explicit opens may fall back to full loading on a scan-limit error.
type SessionHeaderScanLimitError ¶
type SessionHeaderScanLimitError struct{ Path string }
SessionHeaderScanLimitError reports that bounded discovery could not reach a header.
func (*SessionHeaderScanLimitError) Error ¶
func (err *SessionHeaderScanLimitError) Error() string
type SessionImportFileNotFoundError ¶
type SessionImportFileNotFoundError struct{ FilePath string }
SessionImportFileNotFoundError reports a session import source that does not exist. Mirrors upstream SessionImportFileNotFoundError (agent-session-runtime.ts:46-54).
func (*SessionImportFileNotFoundError) Error ¶
func (err *SessionImportFileNotFoundError) Error() string
type SessionInfo ¶
type SessionInfo struct {
Path string
ID string
CWD string
Name string // user-set name (via /name): empty when unset
ParentSessionPath 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 = sessionentry.SessionInfoEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type SessionList ¶
type SessionList struct {
// OnSelect runs with the selected session's path on the confirm key.
OnSelect func(path string)
// OnCancel runs on the cancel key.
OnCancel func()
// OnExit is the host's exit hook (session-selector.ts:302 onExit); the list never raises it itself.
OnExit func()
// OnDeleteConfirmationChange runs with the path awaiting delete confirmation, or "" (upstream null) when the confirmation ends.
OnDeleteConfirmationChange func(path string)
// contains filtered or unexported fields
}
SessionList is upstream's SessionList (session-selector.ts): the session rows of a SessionSelectorComponent, the component the host focuses. Its callbacks run when the selector handles the confirm or cancel key and when the delete confirmation changes.
func (*SessionList) GetSelectedSessionPath ¶
func (l *SessionList) GetSelectedSessionPath() string
GetSelectedSessionPath returns the path of the highlighted session, or "" when no row is visible (SessionList.getSelectedSessionPath).
func (*SessionList) HandleInput ¶
func (l *SessionList) HandleInput(data string)
HandleInput delegates to the selector's key handling (SessionList.handleInput).
type SessionListOptions ¶
type SessionListOptions struct {
Context context.Context
OnProgress SessionListProgress
}
SessionListOptions supplies cancellation and progress for session discovery.
type SessionListProgress ¶
type SessionListProgress func(loaded, total int, partial []SessionInfo)
SessionListProgress receives completed-file counts. A nil partial means no snapshot was published; a non-nil empty slice is an empty published snapshot.
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. It carries the static half of Pi's SessionManager (create, open, forkFrom, getDefaultSessionDir). Ports packages/coding-agent/src/core/session-manager.ts
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 extracts the chosen root-to-leaf path with resolved labels into a fresh Session. In-memory sessions stay in memory. A persisted clone is written immediately only when its path contains a user or assistant message; otherwise its first such message creates the file. The records of a persisted source are streamed from the source to the new file one at a time and the clone opens that file as a resume does, so the branch is never held decoded.
func (*SessionManager) Create ¶
func (sm *SessionManager) Create(id, parentSessionPath string) (*Session, error)
Create validates a supplied session ID or generates an omitted one, then assigns the deferred session file path. parentSessionPath records a source session when supplied.
func (*SessionManager) Current ¶
func (sm *SessionManager) Current() *Session
Current returns the active session.
func (*SessionManager) DeleteSession ¶
func (sm *SessionManager) DeleteSession(path string) error
DeleteSession deletes a session file within the listed root, trying trash before unlink. A file that is already gone counts as success, as in the selector.
func (*SessionManager) FindByID ¶
func (sm *SessionManager) FindByID(id string) string
FindByID finds an exact header ID without reading transcript bodies. A custom session directory is filtered by cwd; discovery errors are best-effort.
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, idOption ...string) (*Session, error)
ForkFromFile copies every non-header entry from sourcePath into a new JSONL. An optional ID is validated and used verbatim; omission generates a UUIDv7. The header records the absolute source path as parentSession. Unlike Clone, this preserves the complete entry tree and writes the file immediately.
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(options ...SessionListOptions) ([]SessionInfo, error)
ListAllSessions returns every valid session JSONL under <agentDir>/sessions/*/*.jsonl, newest message activity first. Mirrors upstream session selector "All" scope.
func (*SessionManager) ListCurrentSessions ¶
func (sm *SessionManager) ListCurrentSessions(options ...SessionListOptions) ([]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(options ...SessionListOptions) ([]SessionInfo, error)
ListSessions returns every valid jsonl in this manager's session directory, newest message activity 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 and migrates a session JSONL and makes it current. A missing path starts a fresh session at that exact path, with persistence deferred until the first user or assistant message.
func (*SessionManager) Open ¶
func (sm *SessionManager) Open(path string, cwdOverride ...string) (*Session, error)
Open opens an explicit session file, with an optional effective working-directory override. Like Pi's SessionManager.open, it first creates the manager's session directory: the caller passes the explicit session directory, else the file's parent (session-manager.ts:1784-1785).
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 SessionMessage ¶
type SessionMessage = extension.SessionMessage
SessionMessage is the union appendMessage takes (session-manager.ts: Message | CustomMessage | BashExecutionMessage): an agent.AgentMessage, which carries the LLM messages and the custom messages in AgentMessage.Custom, or a BashExecutionMessage.
type SessionProjection ¶
type SessionProjection = sessionentry.SessionProjection
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
func BuildSessionProjection ¶
func BuildSessionProjection(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) SessionProjection
BuildSessionProjection projects the branch of entries that ends at leafID: the compaction-aware entries, their model-visible messages, and the latest thinking level and model on the branch. It ports session-manager.ts buildSessionProjection with BuildSessionContext's leaf rules: no leafID selects the last entry, an unknown ID falls back to it, and an explicit nil is an empty branch. For a branch already walked from root to leaf, use ProjectSessionPath.
func ProjectSessionPath ¶
func ProjectSessionPath(path []SessionEntry) SessionProjection
ProjectSessionPath projects a root-to-leaf entry path as it stands, without walking parent links again. Compaction preparation uses it on SessionManager.getBranch() output (compaction.ts prepareCompaction passes that path to buildSessionProjection, which returns the same projection for a chained path).
type SessionSelectorComponent ¶
func NewSessionSelectorComponent ¶
func NewSessionSelectorComponent(currentSessionsLoader, allSessionsLoader SessionsLoader, onSelect func(sessionPath string), onCancel, onExit, requestRender func(), options *SessionSelectorOptions, currentSessionFilePath ...string) *SessionSelectorComponent
NewSessionSelectorComponent is the constructor of session-selector.ts:757-770. onSelect receives the chosen session path, onCancel runs on the cancel key, onExit is the host's exit hook, and requestRender repaints after an asynchronous change. Both loaders start on demand: the current scope loads at once, the all scope the first time it is shown. A trailing currentSessionFilePath marks the current session.
func (*SessionSelectorComponent) Cancelled ¶
func (s *SessionSelectorComponent) Cancelled() bool
func (*SessionSelectorComponent) CapturesViewportInput ¶
func (s *SessionSelectorComponent) CapturesViewportInput() bool
CapturesViewportInput is session-selector.ts capturesViewportInput: the list takes the fullscreen viewport keys except while renaming.
func (*SessionSelectorComponent) Done ¶
func (s *SessionSelectorComponent) Done() bool
func (*SessionSelectorComponent) Focused ¶
func (s *SessionSelectorComponent) Focused() bool
Focused reports whether the session list holds the TUI focus (upstream `get focused`).
func (*SessionSelectorComponent) GetSessionList ¶
func (s *SessionSelectorComponent) GetSessionList() *SessionList
GetSessionList returns the session list (session-selector.ts getSessionList).
func (*SessionSelectorComponent) HandleInput ¶
func (s *SessionSelectorComponent) HandleInput(data string)
func (*SessionSelectorComponent) IsDirty ¶
func (s *SessionSelectorComponent) IsDirty() bool
IsDirty is always true: loads, status expiry and rename completion change what the selector renders without invalidating it, so a parent Container must render it every frame.
func (*SessionSelectorComponent) NativeNode ¶
func (s *SessionSelectorComponent) NativeNode() (frontend.Node, bool)
NativeNode reports the session list as a selector whose item ids are session paths. Rename mode's text field is not a list, so the dock keeps drawing it as lines.
func (*SessionSelectorComponent) SelectedPath ¶
func (s *SessionSelectorComponent) SelectedPath() string
func (*SessionSelectorComponent) SetFocused ¶
func (s *SessionSelectorComponent) SetFocused(focused bool)
SetFocused propagates TUI focus to the session list's search input and to the rename input, which emit the hardware-cursor marker only while focused (upstream `set focused`, session-selector.ts:733-740).
type SessionSelectorOptions ¶
type SessionSelectorOptions struct {
RenameSession func(sessionPath, name string) error
ShowRenameHint *bool
Keybindings *KeybindingsManager
DeleteSession func(sessionPath string) sessionDeleteResult
}
SessionSelectorOptions is the `options` object of session-selector.ts:764-768. RenameSession is the rename operation (a nil one disables renaming); ShowRenameHint defaults to whether renaming is possible; Keybindings defaults to the configured manager. DeleteSession is PiG's guard on the delete operation and defaults to deleteSessionFile (session-selector.ts:826).
type SessionShareDestination ¶
type SessionShareDestination string
SessionShareDestination selects where /share uploads (settings-schema.ts SessionShareDestination).
const ( )
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 = sessionentry.SessionTreeNode
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
type SessionUsageBreakdown ¶
SessionUsageBreakdown attributes billed usage to a model or to host-side summaries.
type SessionsLoader ¶
type SessionsLoader func(ctx context.Context, onProgress SessionListProgress) ([]SessionInfo, error)
SessionsLoader is session-selector.ts:649 SessionsLoader: the awaited Promise is the blocking call, the AbortSignal is ctx, and onProgress receives partial listings.
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 is the configured name. JSON and SettingsManager.SetTheme preserve explicitly empty values.
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 QuietStartup `json:"quietStartup,omitempty"`
Packages []PackageSource `json:"packages,omitzero"`
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"`
HTTPProxy string `json:"httpProxy,omitempty"`
WebSocketConnectTimeoutMs *int `json:"websocketConnectTimeoutMs,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"`
// ExtensionChangelogVersions records the last changelog version seen per extension package, keyed by GetSourcePackageKey.
// Mirrors upstream settings.extensionChangelogVersions (settings-schema.ts).
ExtensionChangelogVersions map[string]string `json:"extensionChangelogVersions,omitzero"`
// 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: fullscreen.
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 FullscreenExitOutput `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"`
// FullscreenWheelScrollLines holds the authored `fullscreenWheelScrollLines` JSON value, a line count or "auto". GetFullscreenWheelScrollLines validates it. A present JSON null is kept because it overrides a lower layer.
FullscreenWheelScrollLines json.RawMessage `json:"fullscreenWheelScrollLines,omitempty"`
// DeviceID is the stable UUID of this installation. Only the global layer is read for it: GetOrCreateDeviceID ignores project settings.
// Mirrors upstream settings.deviceId (settings-manager.ts:156).
DeviceID string `json:"deviceId,omitempty"`
// Codemode configures how the codemode tool presents tools. Mirrors upstream settings.codemode (settings-manager.ts:176).
Codemode *CodemodeSettings `json:"codemode,omitempty"`
// MaskSecretInput controls configurable login-input privacy. Nil means true; false restores Pi's plain-text prompts.
MaskSecretInput *bool `json:"maskSecretInput,omitempty"`
// ExtensionsAutoUpgrade runs the Go extension upgrade rules without asking when an extension fails to build for an older SDK, and after `pig update`. Global setting only; nil means false.
// pig additive (D109): Pi loads extension source in process and has no SDK to drift from. Pi's `extensions` setting is an array, so the key cannot nest under it.
ExtensionsAutoUpgrade *bool `json:"extensionsAutoUpgrade,omitempty"`
// ExtensionsTypescriptRuntime names the runtime that runs TypeScript and JavaScript extensions: "node" (the default) or a runtime an extension or Piglet installed into the runtime slot. PIG_TS_RUNTIME overrides it. Global setting only.
// pig additive (D19): Pi runs extensions inside its own Node process. Pi's `extensions` setting is an array, so the key cannot nest under it.
ExtensionsTypescriptRuntime *string `json:"extensionsTypescriptRuntime,omitempty"`
// CollapseChangelog shows condensed startup update notices. The /changelog command always shows every released entry.
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"`
SessionShareDestination SessionShareDestination `json:"sessionShareDestination,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"`
// SelfUpdateCommand is the argv `pi update` runs to update the program itself, with {packageName}, {version}
// and {installSpec} placeholders. Only the global settings file is read for it, so a project cannot inject a
// command; PI_SELF_UPDATE_COMMAND takes precedence.
// Mirrors upstream settings.selfUpdateCommand (settings-schema.ts).
SelfUpdateCommand []string `json:"selfUpdateCommand,omitzero"`
// 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 ThemeOverride ¶
ThemeOverride returns ApplyOverrides input that selects theme, as Pi's applyOverrides({theme}). An empty name is a selection, not an omitted key.
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) GetDefaultTools ¶
GetDefaultTools returns the resolved `defaultTools` selection, or nil when no settings layer sets it: plain names replace the built-in defaults, then `+name` and `-name` entries apply in order. Mirrors upstream getDefaultTools (settings-manager.ts:1430-1434).
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) GetMaskSecretInput ¶
GetMaskSecretInput returns the login-input privacy setting, enabled by default.
func (Settings) GetOutputPad ¶
GetOutputPad returns zero only for an explicit zero setting, and one otherwise.
func (Settings) GetQuietStartup ¶
func (s Settings) GetQuietStartup() QuietStartup
GetQuietStartup returns the quiet startup setting: true, "header" or false.
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 after migrateSettings' rewrites.
type SettingsCallbacks ¶
type SettingsCallbacks struct {
OnAutoCompactChange func(enabled bool)
OnShowImagesChange func(enabled bool)
OnImageWidthCellsChange func(width int)
OnAutoResizeImagesChange func(enabled bool)
OnBlockImagesChange func(blocked bool)
OnEnableSkillCommandsChange func(enabled bool)
OnSteeringModeChange func(mode string)
OnFollowUpModeChange func(mode string)
OnTransportChange func(transport string)
OnHttpIdleTimeoutMsChange func(timeoutMs int)
OnCacheWarmingModeChange func(mode CacheWarmingMode)
OnModelThinkingLevelChange func(provider, modelID, level string)
OnModelThinkingLevelRemove func(provider, modelID string)
OnThemeChange func(theme string)
OnThemePreview func(theme string)
OnHideThinkingBlockChange func(hidden bool)
OnMermaidRenderingModeChange func(mode MermaidRenderingMode)
OnShowCacheMissNoticesChange func(shown bool)
OnCollapseChangelogChange func(collapsed bool)
OnEnableInstallTelemetryChange func(enabled bool)
OnDoubleEscapeActionChange func(action string)
OnTreeFilterModeChange func(mode string)
OnShowHardwareCursorChange func(enabled bool)
OnEditorPaddingXChange func(padding int)
OnOutputPadChange func(padding OutputPad)
OnAutocompleteMaxVisibleChange func(maxVisible int)
OnQuietStartupChange func(quiet QuietStartup)
OnDefaultProjectTrustChange func(defaultProjectTrust string)
OnClearOnShrinkChange func(enabled bool)
OnShowTerminalProgressChange func(enabled bool)
OnTuiModeChange func(mode string)
OnFullscreenExitOutputChange func(output FullscreenExitOutput)
OnFullscreenScrollbarChange func(mode string)
OnFullscreenCopyOnSelectChange func(enabled bool)
OnFullscreenWheelScrollLinesChange func(lines WheelScrollLines)
OnWarningsChange func(warnings WarningSettings)
// OnMaskSecretInputChange handles the PiG-only "Mask secret input" row.
// pig divergence (D80): configurable input privacy leaves the upstream setting order intact.
OnMaskSecretInputChange func(enabled bool)
OnCancel func()
}
SettingsCallbacks is upstream's SettingsCallbacks. The selector skips a callback that is nil; upstream's TypeScript callers always supply every one.
type SettingsConfig ¶
type SettingsConfig struct {
AutoCompact bool
DefaultModel string
CurrentModel *ai.Model
AvailableDefaultModels []*ai.Model
ShowImages bool
ImageWidthCells int
AutoResizeImages bool
BlockImages bool
EnableSkillCommands bool
SteeringMode string
FollowUpMode string
Transport string
HttpIdleTimeoutMs int
CacheWarmingMode CacheWarmingMode
ThinkingLevel string
AvailableThinkingLevels []string
ModelThinkingLevels map[string]string
CurrentTheme string
TerminalTheme tui.TerminalTheme
AvailableThemes []string
HideThinkingBlock bool
MermaidRenderingMode MermaidRenderingMode
ShowCacheMissNotices bool
CollapseChangelog bool
EnableInstallTelemetry bool
DoubleEscapeAction string
TreeFilterMode string
ShowHardwareCursor bool
EditorPaddingX int
OutputPad OutputPad
AutocompleteMaxVisible int
QuietStartup QuietStartup
DefaultProjectTrust string
ClearOnShrink bool
ShowTerminalProgress bool
TuiMode string
FullscreenExitOutput FullscreenExitOutput
FullscreenScrollbar string
FullscreenCopyOnSelect bool
// FullscreenWheelScrollLines is upstream's WheelScrollLines: "auto" or a line count.
FullscreenWheelScrollLines WheelScrollLines
Warnings WarningSettings
// MaskSecretInput feeds the PiG-only "Mask secret input" row.
// pig divergence (D80): configurable input privacy leaves the upstream setting order intact.
MaskSecretInput bool
}
SettingsConfig is upstream's SettingsConfig: the values the selector shows.
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 NewInMemorySettingsManager ¶
func NewInMemorySettingsManager(settings Settings) *SettingsManager
NewInMemorySettingsManager creates an independent settings manager without file I/O. Ports packages/coding-agent/src/core/settings-manager.ts:403-410.
func NewSettingsManager ¶
func NewSettingsManager(cwd, agentDir string) *SettingsManager
NewSettingsManager creates a SettingsManager for the given directories.
func NewSettingsManagerFromStorage ¶
func NewSettingsManagerFromStorage(storage SettingsStorage, options SettingsManagerCreateOptions) *SettingsManager
NewSettingsManagerFromStorage is upstream's SettingsManager.fromStorage(storage, options). upstream: settings-manager.ts:325-327
func NewSettingsManagerWithOptions ¶
func NewSettingsManagerWithOptions(cwd, agentDir string, options SettingsManagerCreateOptions) *SettingsManager
NewSettingsManagerWithOptions is upstream's SettingsManager.create(cwd, agentDir, options). upstream: settings-manager.ts:440-452
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, or an empty list, and clears them.
func (*SettingsManager) ExtensionSettings ¶
func (sm *SettingsManager) ExtensionSettings() extension.Settings
ExtensionSettings is GetSettings as the JSON object extensions read: a copy that a change does not reach back into the manager through.
upstream: settings-manager.ts:562-564 (getSettings), loader.ts:411-414
func (*SettingsManager) ExtensionSettingsJSON ¶
func (sm *SettingsManager) ExtensionSettingsJSON() json.RawMessage
ExtensionSettingsJSON is ExtensionSettings() as JSON with its members in the order Pi's getSettings() object lists them, the settings object an extension state push carries. It is encoded once per settings generation and shared: the caller must not change it.
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) GetAllModelThinkingLevels ¶
func (sm *SettingsManager) GetAllModelThinkingLevels() map[string]ai.ThinkingLevel
GetAllModelThinkingLevels returns a copy of the merged per-model default thinking levels keyed by provider/modelID. Mirrors upstream getAllModelThinkingLevels.
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 the global compaction toggle independently of model token validation.
func (*SettingsManager) GetCompactionKeepRecentTokens ¶
func (sm *SettingsManager) GetCompactionKeepRecentTokens(model ...*ai.Model) (int, error)
GetCompactionKeepRecentTokens resolves and validates the retention setting for the optional model (upstream getCompactionKeepRecentTokens(model?)).
func (*SettingsManager) GetCompactionReserveTokens ¶
func (sm *SettingsManager) GetCompactionReserveTokens(model ...*ai.Model) (int, error)
GetCompactionReserveTokens resolves and validates the reserve token setting for the optional model (upstream getCompactionReserveTokens(model?)).
func (*SettingsManager) GetCompactionSettings ¶
func (sm *SettingsManager) GetCompactionSettings(model ...*ai.Model) (CompactionConfig, error)
GetCompactionSettings resolves ordinary settings and rejects invalid authored token values. The optional model selects the compaction.modelOverrides entry for its provider and ID, as upstream getCompactionSettings(model?: Pick<Model, "provider" | "id">).
func (*SettingsManager) GetDefaultModel ¶
func (sm *SettingsManager) GetDefaultModel() string
GetDefaultModel returns the configured default model, or "".
func (*SettingsManager) GetDefaultProjectTrust ¶
func (sm *SettingsManager) GetDefaultProjectTrust() DefaultProjectTrust
GetDefaultProjectTrust returns the fallback project-trust mode, "ask" unless the global setting is "always" or "never". upstream: settings-manager.ts:1100 getDefaultProjectTrust
func (*SettingsManager) GetDefaultProvider ¶
func (sm *SettingsManager) GetDefaultProvider() string
GetDefaultProvider returns the configured default provider, or "".
func (*SettingsManager) GetDefaultThinkingLevel ¶
func (sm *SettingsManager) GetDefaultThinkingLevel() ai.ThinkingLevel
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
GetEnableSkillCommands returns whether skill commands are shown in autocomplete. Default: true. Mirrors upstream getEnableSkillCommands (settings-manager.ts:1264-1266).
func (*SettingsManager) GetEnabledModels ¶
func (sm *SettingsManager) GetEnabledModels() []string
GetEnabledModels returns the list of enabled models for Ctrl+P cycling, or nil.
func (*SettingsManager) GetExtensionChangelogVersion ¶
func (sm *SettingsManager) GetExtensionChangelogVersion(key string) (string, bool)
GetExtensionChangelogVersion returns the last changelog version seen for the extension package key (GetSourcePackageKey), if any. Mirrors upstream getExtensionChangelogVersion (settings-manager.ts).
func (*SettingsManager) GetExtensionPaths ¶
func (sm *SettingsManager) GetExtensionPaths() []string
GetExtensionPaths returns the configured extension paths, or an empty list.
func (*SettingsManager) GetExtensionsAutoUpgrade ¶
func (sm *SettingsManager) GetExtensionsAutoUpgrade() bool
GetExtensionsAutoUpgrade reports whether the global settings turn on the automatic Go extension upgrade. It is off unless set, and a project file cannot turn it on. pig additive (D109): see Settings.ExtensionsAutoUpgrade.
func (*SettingsManager) GetExtensionsTypescriptRuntime ¶
func (sm *SettingsManager) GetExtensionsTypescriptRuntime() string
GetExtensionsTypescriptRuntime returns the global extensionsTypescriptRuntime setting, or "" when it is unset. A project file cannot set it. pig additive (D19): see Settings.ExtensionsTypescriptRuntime.
func (*SettingsManager) GetExternalEditorCommand ¶
func (sm *SettingsManager) GetExternalEditorCommand() string
GetExternalEditorCommand resolves a nonblank configured command, VISUAL, EDITOR, then the platform default, without trimming the selected 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() FullscreenExitOutput
func (*SettingsManager) GetFullscreenScrollbar ¶
func (sm *SettingsManager) GetFullscreenScrollbar() string
func (*SettingsManager) GetFullscreenWheelScrollLines ¶
func (sm *SettingsManager) GetFullscreenWheelScrollLines() WheelScrollLines
GetFullscreenWheelScrollLines returns the wheel line setting: a finite number floored and clamped to 1-100, otherwise auto. Mirrors upstream getFullscreenWheelScrollLines (settings-manager.ts:1386-1391).
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() MermaidRenderingMode
GetMermaidRenderingMode returns "off" or "final" when the markdown.mermaid setting says so, otherwise "streaming" (settings-manager.ts:1512-1515).
func (*SettingsManager) GetModelThinkingLevel ¶
func (sm *SettingsManager) GetModelThinkingLevel(provider, modelID string) ai.ThinkingLevel
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) GetOrCreateDeviceID ¶
func (sm *SettingsManager) GetOrCreateDeviceID() string
GetOrCreateDeviceID returns the stable ID of this installation, e.g. sent to OpenAI as its agent host ID, and creates it on first use. Project settings are ignored so a committed project settings file cannot give every clone the same ID. A global file that does not parse keeps the new ID in memory only, as upstream's save() returns before writing then. Mirrors upstream getOrCreateDeviceId (settings-manager.ts:1172-1179).
func (*SettingsManager) GetOutputPad ¶
func (sm *SettingsManager) GetOutputPad() OutputPad
GetOutputPad returns horizontal chat output padding.
func (*SettingsManager) GetPackages ¶
func (sm *SettingsManager) GetPackages() []PackageSource
GetPackages returns the configured package sources, or an empty list.
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, or an empty list.
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 is the request timeoutMs (GetProviderRequestTimeoutMs), not the dispatcher's idle timeout; 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() QuietStartup
GetQuietStartup returns the quiet startup setting: true, "header" or false (settings-manager.ts:1089-1092).
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) GetSessionShareDestination ¶
func (sm *SettingsManager) GetSessionShareDestination() SessionShareDestination
GetSessionShareDestination returns the configured /share destination. Values other than "gist" and "radius" read as "auto" (settings-manager.ts getSessionShareDestination). pig divergence (D64): /share uploads to the PiG gateway for every value; the setting is kept for shared settings files and the SDK.
func (*SettingsManager) GetSettings ¶
func (sm *SettingsManager) GetSettings() Settings
GetSettings returns a copy of the effective settings: global and project settings merged, with overrides. Mirrors upstream getSettings (settings-manager.ts:564-566).
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, or an empty list.
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 fixed theme name, or "" for an automatic slash-separated theme setting.
func (*SettingsManager) GetThemePaths ¶
func (sm *SettingsManager) GetThemePaths() []string
GetThemePaths returns the configured theme paths, or an empty list.
func (*SettingsManager) GetThemeSetting ¶
func (sm *SettingsManager) GetThemeSetting() *string
GetThemeSetting returns the selected setting, preserving an omitted value separately from an explicitly empty name.
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() tui.TuiMode
GetTuiMode returns the terminal UI mode: "regular" only when the setting says so, otherwise "fullscreen" (settings-manager.ts:1348-1350).
func (*SettingsManager) GetWarnings ¶
func (sm *SettingsManager) GetWarnings() WarningSettings
GetWarnings returns warning settings.
func (*SettingsManager) GetWebSocketConnectTimeoutMs ¶
func (sm *SettingsManager) GetWebSocketConnectTimeoutMs() (*int, error)
GetWebSocketConnectTimeoutMs returns the optional opening-handshake timeout; zero disables it.
func (*SettingsManager) GlobalPath ¶
func (sm *SettingsManager) GlobalPath() string
GlobalPath returns the global settings file path, or empty for memory storage.
func (*SettingsManager) GlobalSettingsPath ¶
func (sm *SettingsManager) GlobalSettingsPath() string
GlobalSettingsPath returns the global settings file path, or empty for memory storage.
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 reloads the backing settings layers and discards transient overrides. Previously recorded errors remain until DrainErrors.
func (*SettingsManager) ObserveChange ¶
func (sm *SettingsManager) ObserveChange(observe func()) func()
ObserveChange registers observe to run after every change of the effective settings: a setter, a reload, a trust change and an override. A change that leaves the merged settings equal still reports. observe runs on the goroutine that made the change, with the manager's lock held for writing, so it must return at once and must not call the manager. The returned function removes it and can be called repeatedly.
func (*SettingsManager) Reload ¶
func (sm *SettingsManager) Reload()
Reload refreshes the merged view from file or memory storage after earlier writes finish.
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) ResolvedDefaultTools ¶
func (sm *SettingsManager) ResolvedDefaultTools() []string
ResolvedDefaultTools returns the tools enabled at startup: the `defaultTools` setting, or the built-in defaults when no settings layer sets it. Mirrors upstream `getDefaultTools() ?? DEFAULT_TOOL_NAMES` (agent-session.ts:3593).
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) SetDefaultProjectTrust ¶
func (sm *SettingsManager) SetDefaultProjectTrust(trust DefaultProjectTrust) error
SetDefaultProjectTrust stores the fallback project-trust mode in the global settings and saves. upstream: settings-manager.ts:1105 setDefaultProjectTrust
func (*SettingsManager) SetDefaultProvider ¶
func (sm *SettingsManager) SetDefaultProvider(p string) error
SetDefaultProvider sets the default provider.
func (*SettingsManager) SetDefaultThinkingLevel ¶
func (sm *SettingsManager) SetDefaultThinkingLevel(level ai.ThinkingLevel) 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) SetExtensionChangelogVersion ¶
func (sm *SettingsManager) SetExtensionChangelogVersion(key, version string) error
SetExtensionChangelogVersion records that the user has seen the changelog of the extension package key up to version. Persists to global settings, changing only that key. Mirrors upstream setExtensionChangelogVersion.
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 FullscreenExitOutput) error
func (*SettingsManager) SetFullscreenScrollbar ¶
func (sm *SettingsManager) SetFullscreenScrollbar(mode string) error
func (*SettingsManager) SetFullscreenWheelScrollLines ¶
func (sm *SettingsManager) SetFullscreenWheelScrollLines(lines WheelScrollLines) error
SetFullscreenWheelScrollLines saves the wheel line setting to global settings: auto, or a count floored and clamped to 1-100. Mirrors upstream setFullscreenWheelScrollLines (settings-manager.ts:1394-1399).
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) SetMaskSecretInput ¶
func (sm *SettingsManager) SetMaskSecretInput(enabled bool) error
SetMaskSecretInput sets the PiG-only login-input privacy setting. pig divergence (D80): configurable input privacy leaves the upstream setting order intact.
func (*SettingsManager) SetMermaidRenderingMode ¶
func (sm *SettingsManager) SetMermaidRenderingMode(mode MermaidRenderingMode) error
func (*SettingsManager) SetModelThinkingLevel ¶
func (sm *SettingsManager) SetModelThinkingLevel(provider, modelID string, level ai.ThinkingLevel) 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 OutputPad) 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, including an explicitly empty array.
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, including an explicitly empty array.
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 without reloading global settings. Unchanged trust preserves the current merged view. Ports packages/coding-agent/src/core/settings-manager.ts:515-537.
func (*SettingsManager) SetPromptTemplatePaths ¶
func (sm *SettingsManager) SetPromptTemplatePaths(paths []string) error
func (*SettingsManager) SetQuietStartup ¶
func (sm *SettingsManager) SetQuietStartup(quiet QuietStartup) error
SetQuietStartup sets the global quiet startup setting.
func (*SettingsManager) SetRetryEnabled ¶
func (sm *SettingsManager) SetRetryEnabled(enabled bool) error
SetRetryEnabled enables or disables auto-retry.
func (*SettingsManager) SetSessionShareDestination ¶
func (sm *SettingsManager) SetSessionShareDestination(destination SessionShareDestination) error
SetSessionShareDestination sets the /share destination in the global settings.
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
SetTheme stores an explicit default theme; an empty name is not an omitted setting.
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 tui.TuiMode) error
SetTuiMode sets the terminal UI mode.
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 and refreshes the merged view, then saves to the selected backing storage. Like Pi's setters (settings-manager.ts:668-682), the change stays in effect in memory when the global file had parse errors, which skips the save, or when the save fails.
func (*SettingsManager) UpdateProject ¶
func (sm *SettingsManager) UpdateProject(fn func(*Settings)) error
UpdateProject applies fn to trusted project settings and refreshes the merged view, then saves to the selected storage. Like Pi's saveProjectSettings (settings-manager.ts:684-698), an untrusted project refuses the change, and otherwise the change stays in effect in memory when the project file had parse errors, which skips the save, or when the save fails.
type SettingsManagerCreateOptions ¶
type SettingsManagerCreateOptions struct {
// ProjectTrusted is whether project settings are read; nil is true.
// upstream: settings-manager.ts:465 `options.projectTrusted ?? true`
ProjectTrusted *bool
}
SettingsManagerCreateOptions are the options of SettingsManager.create. upstream: settings-manager.ts:292-294
type SettingsSelectorComponent ¶
SettingsSelectorComponent is upstream's SettingsSelectorComponent: a bordered settings list whose changes reach the callbacks.
func NewSettingsSelectorComponent ¶
func NewSettingsSelectorComponent(config SettingsConfig, callbacks SettingsCallbacks) *SettingsSelectorComponent
NewSettingsSelectorComponent builds the selector's rows from config in upstream's order and routes each change to its callback.
func (*SettingsSelectorComponent) GetSettingsList ¶
func (s *SettingsSelectorComponent) GetSettingsList() *tui.SettingsList
GetSettingsList returns the list that takes the selector's input.
func (*SettingsSelectorComponent) IsDirty ¶
func (s *SettingsSelectorComponent) IsDirty() bool
IsDirty and NeedsRedraw report the list's invalidation, because input changes the list without invalidating the container that holds it and a parent container caches this component's rendered lines until it is dirty.
func (*SettingsSelectorComponent) NativeNode ¶
func (s *SettingsSelectorComponent) NativeNode() (frontend.Node, bool)
NativeNode reports the selector's settings list, or the submenu it has open.
func (*SettingsSelectorComponent) NeedsRedraw ¶
func (s *SettingsSelectorComponent) NeedsRedraw() bool
NeedsRedraw clears the container's invalidation and reports the list's without clearing it. A parent container consumes the flag before it renders this component, and the list is a child of the embedded container, which re-renders it only while the list is dirty; clearing the list's flag here would leave that container's cached lines in place.
func (*SettingsSelectorComponent) SurfaceLive ¶
func (s *SettingsSelectorComponent) SurfaceLive() bool
pig additive (D91): SurfaceLive reports that the list changes without invalidating the selector, as IsDirty does, so a TuiSurface rebuilds it every frame.
type SettingsStorage ¶
type SettingsStorage interface {
WithLock(scope string, fn func(current *string) (*string, error)) error
}
SettingsStorage is Pi's SettingsStorage (settings-manager.ts:166): the backend of SettingsManager.fromStorage. WithLock runs fn on the current text of the scope's settings ("global" or "project", nil when there is none); fn returns the text to store, nil to leave it, or an error that WithLock returns.
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 {
SourceInfo PiSourceInfo
Name string
Description string
DisableModelInvocation bool
// Body is the markdown content (stripped of frontmatter).
Body string
// FilePath is the source Markdown file.
FilePath string
// BaseDir is the skill's containing directory: used so callers can
// resolve referenced sibling files.
BaseDir string
}
SkillDef is a parsed Markdown skill with frontmatter and 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 DeduplicateSkillsWithDiagnostics ¶
func DeduplicateSkillsWithDiagnostics(defs []*SkillDef) ([]*SkillDef, []extension.ResourceDiagnostic)
DeduplicateSkillsWithDiagnostics keeps the first name, silently ignores repeated real paths, and reports later same-name definitions in input order. Ports packages/coding-agent/src/core/skills.ts
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 LoadSkillsFromPath ¶
LoadSkillsFromPath loads one or more skills from a path in discovery order, without sorting by frontmatter name. 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 SkillFrontmatter ¶
SkillFrontmatter is upstream's SkillFrontmatter (core/skills.ts:67): the parsed header of a skill file. The three named fields have typed accessors; every other key stays in the map.
func ParseSkillFrontmatter ¶
func ParseSkillFrontmatter(content string) (SkillFrontmatter, string, error)
ParseSkillFrontmatter splits a skill file into its header and trimmed body, as upstream's parseFrontmatter<SkillFrontmatter> does.
func (SkillFrontmatter) Description ¶
func (f SkillFrontmatter) Description() string
Description is the skill's `description`, or "" when absent.
func (SkillFrontmatter) DisableModelInvocation ¶
func (f SkillFrontmatter) DisableModelInvocation() bool
DisableModelInvocation is the skill's `disable-model-invocation` flag.
func (SkillFrontmatter) Name ¶
func (f SkillFrontmatter) Name() string
Name is the skill's `name`, or "" when absent.
type SlashCommand ¶
type SlashCommand struct {
Name string
Description string
Handler func(ctx *ExtensionContext, args string) error
}
SlashCommand is a command registered via /name.
type SlashCommandCatalog ¶
type SlashCommandCatalog struct {
Runner ExtensionCommandLister
PromptTemplates []PromptTemplate
Skills []*SkillDef
CWD string
AgentDir string
SourceInfo map[string]ResourceSourceInfo
}
SlashCommandCatalog lists the commands upstream AgentSession's getCommands (agent-session.ts _bindExtensionCore) and RPC get_commands report: extension commands, then prompt templates, then skills.
func (SlashCommandCatalog) Commands ¶
func (c SlashCommandCatalog) Commands() []SlashCommandInfo
Commands returns the catalog in upstream order.
func (SlashCommandCatalog) SourceInfoForPath ¶
func (c SlashCommandCatalog) SourceInfoForPath(path, kind string) PiSourceInfo
SourceInfoForPath returns the SourceInfo of a resource of kind ("extensions", "prompts" or "skills") loaded from path.
func (SlashCommandCatalog) SubprocessCommands ¶
func (c SlashCommandCatalog) SubprocessCommands() []subprocess.CommandInfo
SubprocessCommands returns SlashCommandCatalog.Commands in the subprocess wire shape.
func (SlashCommandCatalog) WithPromptSources ¶
func (c SlashCommandCatalog) WithPromptSources(templates []PromptTemplate) []PromptTemplate
WithPromptSources returns templates carrying the sourceInfo command discovery reports for them: the provenance recorded for their path, else their own, else the default for their path (resource-loader.ts:880-882 updatePromptsFromPaths).
func (SlashCommandCatalog) WithSkillCommandSources ¶
func (c SlashCommandCatalog) WithSkillCommandSources(skills []*SkillDef) []*SkillDef
WithSkillCommandSources returns skills carrying the sourceInfo SlashCommandCatalog.Commands reports for them: the provenance recorded for their path, else their own, else the default for their path.
func (SlashCommandCatalog) WithSkillSources ¶
func (c SlashCommandCatalog) WithSkillSources(skills []*SkillDef) []*SkillDef
WithSkillSources projects loaded skills with the same resource provenance used by command discovery. Inline skills retain their authored metadata; file-backed skills use resolver and extension-discovery metadata. Ports packages/coding-agent/src/core/resource-loader.ts
type SlashCommandInfo ¶
type SlashCommandInfo = extension.SlashCommandInfo
SlashCommandInfo mirrors upstream SlashCommandInfo (core/slash-commands.ts), the entry type of pi.getCommands() and of RPC get_commands.
type SlashCommandSource ¶
type SlashCommandSource string
SlashCommandSource mirrors upstream's `SlashCommandSource` discriminator.
const ( SlashSourceBuiltin SlashCommandSource = "builtin" SlashSourceExtension SlashCommandSource = "extension" SlashSourcePrompt SlashCommandSource = "prompt" // <agentDir>/prompts/*.md SlashSourceSkill SlashCommandSource = "skill" // /skill:name for each loaded skill )
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)
// AppendThemedText appends Spacer(1) and ThemedText(build, 1, 0): build runs on every render, so the text follows theme changes.
AppendThemedText func(build func() string)
// AppendBlock appends Spacer(1) and Text(text, 1, 1), the confirmation
// block upstream handlers such as handleDebugCommand add. The text is not
// Markdown, so paths keep their backslashes.
AppendBlock func(string)
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
// SelectedModelKey is `provider/id` of the session's selected model, the key of a single-model /session cost total.
SelectedModelKey func() string
ToolNames func() []string
// ToolRenderers returns how HTML exports draw tool calls; see [ExportToolRenderers].
ToolRenderers func() func(name string) *extension.ToolRenderers
// 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
ShowHotkeys func()
ShowChangelog func()
// All registered commands: set by Dispatch before calling Handler
// so /help can enumerate the live set.
AllCommands []HelpCommandInfo
// Session accessors. May be nil; handlers must guard.
CurrentSession func() *Session
// ExportToJsonl writes the current branch to outputPath (upstream session.exportToJsonl). May be nil: /export then
// writes the branch of CurrentSession itself.
ExportToJsonl func(outputPath string) (string, error)
// 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
// ResumeStatus, when set, returns the status /resume shows after LoadSessionPath succeeds. The default is "Resumed session".
ResumeStatus func() string
// ImportSession imports a session JSONL file through the Session and
// reports whether session_before_switch cancelled the switch. Mirrors
// upstream runtimeHost.importFromJsonl.
ImportSession func(inputPath, cwdOverride string) (cancelled bool, err 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
// The prompts of the /tree summarize-branch flow, /import and a missing session cwd are dialogs on the extension dialog
// stack, as upstream awaits them through showExtensionSelector, showExtensionConfirm and showExtensionEditor.
// ShowExtensionSelector returns the chosen option and true, or ("", false) when the selector is dismissed (Esc).
ShowExtensionSelector func(title string, options []string) (string, bool)
// ShowExtensionConfirm shows a Yes/No confirmation and reports whether Yes was chosen. Nil falls back to ShowExtensionSelector.
ShowExtensionConfirm func(title, message string) bool
// ShowTrustSelector invokes OnSelect before restoring the editor so persistence precedes closing the selector.
ShowTrustSelector func(TrustSelectorOptions) (TrustSelection, bool)
// ShowExtensionEditor returns the text and true, or ("", false) when the editor is dismissed (Esc).
ShowExtensionEditor func(title, prefill string) (string, bool)
// ShowBugReportSelector and ShowBugReportEditor are the /bug prompts. Upstream's bug-report.ts builds its own
// ExtensionSelectorComponent (with a description under the title) and ExtensionEditorComponent in the editor slot, outside
// the dialog stack, and reports no blocked status. Each returns the choice or text and true, or ("", false) on Esc.
ShowBugReportSelector func(title string, options []string, description string) (string, bool)
ShowBugReportEditor 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
// CurrentTuiMode returns the running renderer's mode, independent of the saved default. Nil outside the interactive UI.
CurrentTuiMode func() string
// SwitchTuiMode switches the running renderer before the settings list saves a TUI mode, and returns false when the switch is refused. Nil outside the interactive UI.
SwitchTuiMode func(mode string) bool
// ShowSettingsSelector builds the settings selector with done and presents it, blocking until done runs. Upstream's showSelector((done) => ...) does the same.
ShowSettingsSelector func(build func(done func()) *SettingsSelectorComponent)
// PreviewTheme applies a theme setting without saving it. Used by the selector's theme submenu.
PreviewTheme func(setting string)
// ThemeSelection returns the theme setting in effect, or "" when there is none.
ThemeSelection func() string
// SettingsModels returns the models the per-model thinking submenu offers and the session's current model.
SettingsModels func() (available []*ai.Model, current *ai.Model)
// ApplyModelThinkingLevel applies a changed per-model thinking level to the session when it is for the current model. An empty level means the override was cleared.
ApplyModelThinkingLevel func(provider, modelID, level string)
// 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)
// 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()
// 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 starts the change and calls settled
// on the owner loop once it settles, without waiting for it. An accepted
// PickModel selection stays shown and focused until then, as Pi's model
// selector closes only once setModel settles. ShowError reports a failure.
SwitchModel func(spec string, settled func(error))
ShowError func(msg string)
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() error
// 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
// ReloadSavedProjectTrust reports, once per reload, whether the reload saved the implicit project trust decision.
ReloadSavedProjectTrust func() bool
// 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)
// Provider metadata and modal callbacks for /login and /logout.
LoginProviders func() []tui.OAuthProvider
LogoutProviders func() ([]tui.OAuthProvider, error)
SelectAuthProvider func(mode string, providers []tui.OAuthProvider, initialSearch string) (tui.OAuthProvider, bool)
// SelectAuthMethod returns "oauth" or "api_key", or the ID of a provider the top-level menu (nil providers) offers
// directly, such as Radius.
SelectAuthMethod func(providers []tui.OAuthProvider) (choice string, ok bool)
// StartProviderLogin returns errLoginCancelled when the user cancels the login, which reopens the menu it was
// started from.
StartProviderLogin func(provider tui.OAuthProvider) 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
// 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 SlashMatch ¶
type SlashMatch struct {
// Name is the command name as written, without the slash.
Name string
// Args is the argument text: for a built-in, the trimmed remainder of a command that takes arguments; for an extension command,
// everything after the first space (agent-session.ts _tryExecuteExtensionCommand).
Args string
// Builtin or Dynamic is the resolved command.
Builtin *BuiltinSlashCommand
Dynamic *SlashCommand
}
SlashMatch is a submitted line resolved to the command it runs.
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() []HelpCommandInfo
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) DispatchHeadless ¶
func (r *SlashRegistry) DispatchHeadless(sc *SlashContext, line string, extCtx *ExtensionContext) error
DispatchHeadless is SlashRegistry.Dispatch for Session.DispatchSlash, where a built-in without a picker reads its argument instead.
func (*SlashRegistry) IsBuiltin ¶
func (r *SlashRegistry) IsBuiltin(name string) bool
IsBuiltin reports whether name (or an alias) is a built-in command, the commands upstream's onSubmit handles in its builtin chain.
func (*SlashRegistry) Match ¶
func (r *SlashRegistry) Match(line string) (SlashMatch, bool)
Match resolves a submitted line as interactive-mode.ts does. The line is trimmed with ECMAScript whitespace. A built-in matches the exact text "/name" and, when it takes arguments, "/name " followed by anything (one ASCII space: a tab or a no-break space does not separate); any other line is not that built-in. A line that is not a built-in is an extension command when the name before its first space is registered.
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 StdinBuffer ¶
type StdinBuffer = tui.StdinBuffer
StdinBuffer is the shared UTF-16 framing state used by terminal owners.
func NewStdinBuffer ¶
func NewStdinBuffer(options StdinBufferOptions) *StdinBuffer
type StdinBufferOptions ¶
type StdinBufferOptions = tui.StdinBufferOptions
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) NativeNode ¶
func (s *SteppedSubmenu) NativeNode() (frontend.Node, bool)
NativeNode reports the active step's submenu; a step whose labels carry a check column, such as the per-model thinking levels, reports it as Checked.
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 the widget key: one namespace
// for every extension, the host-process ones included (Pi's setExtensionWidget).
SetWidgetSyncFunc(fn func(widgets map[string]*subprocess.PushProxy))
// SetWidgetClearFunc sets a callback for an extension process clearing a widget key it does not hold, so the host-process widget
// under that key goes.
SetWidgetClearFunc(fn func(key string))
// RemoveWidget drops the extension processes' widget under key, which a host-process extension replaced.
RemoveWidget(key string)
// SetFrontend tells extensions whether a frontend session draws
// (StatePayload.frontend, D107).
SetFrontend(on bool)
}
SubprocessUIBridge is the interface satisfied by *subprocess.UIBridge for wiring subprocess extension UI after TUI creation.
pig-specific: no upstream equivalent.
type SyntheticSourceInfoOptions ¶
type SyntheticSourceInfoOptions struct {
Source string
Scope string
Origin string
BaseDir string
// ChangelogPath is the changelog file of the package the resource belongs to, if any.
ChangelogPath string
}
SyntheticSourceInfoOptions is the options object of upstream's createSyntheticSourceInfo; an empty Scope or Origin takes upstream's default.
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.TUI) *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 ThemeFile ¶
ThemeFile is a theme loaded from the file at Path.
func LoadThemeFiles ¶
func LoadThemeFiles(sm *SettingsManager, paths []string) ([]ThemeFile, []extension.ResourceDiagnostic)
LoadThemeFiles loads the themes at paths as resource-loader.ts loadThemes does for DefaultResourceLoader: the first theme of a name wins, and the diagnostics hold the load warnings and the name collisions in order. Theme construction uses the color mode of the settings' terminal capability overrides without the tmux hyperlink probe (resource-loader.ts:884-888). It registers nothing.
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 = sessionentry.ThinkingLevelEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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 ai.ThinkingLevel, availableLevels []ai.ThinkingLevel, onSelect func(level ai.ThinkingLevel), onCancel func(), onSelectAsDefault func(level ai.ThinkingLevel), defaultThinkingLevel ai.ThinkingLevel, ) *ThinkingSelectorComponent
NewThinkingSelectorComponent builds the selector. onSelectAsDefault may be nil, which disables the save binding; defaultThinkingLevel annotates that level's description.
func (*ThinkingSelectorComponent) Focused ¶
func (s *ThinkingSelectorComponent) Focused() bool
Focused reports whether the search input holds the TUI focus (upstream `get focused`).
func (*ThinkingSelectorComponent) GetSelectList ¶
func (s *ThinkingSelectorComponent) GetSelectList() *tui.SelectList
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.
func (*ThinkingSelectorComponent) NativeNode ¶
func (s *ThinkingSelectorComponent) NativeNode() (frontend.Node, bool)
NativeNode reports the levels as a selector whose item ids are the levels; the current level's check column becomes Checked.
func (*ThinkingSelectorComponent) SetFocused ¶
func (s *ThinkingSelectorComponent) SetFocused(focused bool)
SetFocused propagates TUI focus to the search input (upstream `set focused`, thinking-selector.ts:50-53).
type ThinkingSuffixMode ¶
type ThinkingSuffixMode int
ThinkingSuffixMode is ModelReferenceRequest.thinkingSuffix.
const ( // ThinkingSuffixNone keeps the suffix part of the id. ThinkingSuffixNone ThinkingSuffixMode = iota // ThinkingSuffixStrict parses a valid thinking level; any other suffix stays part of the id. ThinkingSuffixStrict // ThinkingSuffixLenient is strict, but an invalid suffix is dropped with a warning. ThinkingSuffixLenient )
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 ToolConflict ¶
ToolConflict is a tool that the extension at Path registered after the extension at Owner, at a different path, already registered it. pig additive (D109): PiG's stale-copy diagnostic needs the owner as data; Pi's conflict carries only the message.
func DetectToolConflicts ¶
func DetectToolConflicts(exts []extension.Extension) []ToolConflict
DetectToolConflicts reports the tool conflicts DetectExtensionConflicts reports, with the path of the extension that owns each tool.
type ToolRendererCard ¶
type ToolRendererCard struct {
Component *tui.ToolExecutionComponent
// contains filtered or unexported fields
}
ToolRendererCard owns one built-in card and its asynchronous invalidations. Its Component is mutated and rendered on the presentation owner loop; Dispose runs off-loop, cancels invalidations and joins all ticker/preview work. An already running filesystem preview finishes before Dispose returns.
func NewToolRendererCard ¶
func NewToolRendererCard(ctx context.Context, name, toolCallId, cwd string, args json.RawMessage, renderers ToolRenderers, requestRender func()) *ToolRendererCard
NewToolRendererCard binds shared renderers to an independent card. An empty pair retains the native card's unregistered-tool path. RequestRender must be safe from a background invalidation.
func (*ToolRendererCard) Dispose ¶
func (card *ToolRendererCard) Dispose()
Dispose cancels the card and joins its existing work. Repeated callers wait for the same disposal. State is fenced before waiting, so rendering cannot start another background task after disposal begins.
type ToolRenderers ¶
type ToolRenderers = extension.ToolRenderers
ToolRenderers is types.ts ToolRenderers (renderShell, renderCall and renderResult of a tool definition): the built-in presentation, without a tool implementation or parameter schema.
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 TrustSelection ¶
type TrustSelection struct {
Trusted bool
Updates []ProjectTrustUpdate
}
type TrustSelectorComponent ¶
func NewTrustSelectorComponent ¶
func NewTrustSelectorComponent(options TrustSelectorOptions) *TrustSelectorComponent
func (*TrustSelectorComponent) HandleInput ¶
func (s *TrustSelectorComponent) HandleInput(data string)
func (*TrustSelectorComponent) NativeNode ¶
func (s *TrustSelectorComponent) NativeNode() (frontend.Node, bool)
NativeNode reports the trust choices as a selector whose item ids are option indexes; the saved decision is Checked. The heading, the folder and the saved and current decisions are the texts above the list.
type TrustSelectorOptions ¶
type TrustSelectorOptions struct {
Cwd string
SavedDecision *ProjectTrustStoreEntry
ProjectTrusted bool
OnSelect func(TrustSelection)
OnCancel func()
}
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, options ...FetchUpdateManifestOptions) (*UpdateManifest, error)
FetchUpdateManifest reads, authenticates, and parses the exact update manifest at rawURL. Explicit updates retry transport failures and transient HTTP statuses twice within one version-check budget; authentication and parsing failures are terminal.
func (*UpdateManifest) PlatformBinary ¶
func (m *UpdateManifest) PlatformBinary() (UpdateBinary, bool)
PlatformBinary returns the manifest's binary for the current platform.
type UsageEntry ¶
type UsageEntry = sessionentry.UsageEntry
The entry values live in internal/sessionentry so coding/extension can name them without an import cycle.
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
type WheelScrollLines ¶
WheelScrollLines is the number of lines a wheel event scrolls, or Auto for velocity-based acceleration (upstream `WheelScrollLines = number | "auto"`). Lines is 1 to 100 when read from settings.
Source Files
¶
- app_keybinding.go
- armin.go
- auth_filter.go
- auth_guidance.go
- auth_warnings.go
- auto_recovery.go
- autocomplete_source_tag.go
- autocomplete_wrappers.go
- bash_executor.go
- before_agent_start_run.go
- bug_report.go
- bug_report_unix.go
- builtin_chat_catalog.go
- cache_stats.go
- cache_warmer.go
- canonical_path_other.go
- canonical_path_win32.go
- chalk_level.go
- chalk_level_unix.go
- changelog.go
- changelog_bundle.go
- changelog_links.go
- chat_viewport.go
- clipboard.go
- clipboard_copy.go
- clipboard_paste.go
- clipboard_pipe_other.go
- clipboard_text.go
- command_argument_completions.go
- compact_read.go
- context_files.go
- crash_log.go
- custom_editor.go
- custom_entry_component.go
- custom_message_route.go
- custom_overlay.go
- custom_overlay_control.go
- debug_log_open_unix.go
- default_models.go
- defaults.go
- earendil_announcement.go
- env_lookup_other.go
- event_bridge.go
- exit_ending.go
- exit_record.go
- exit_record_pidns_linux.go
- exit_record_unix.go
- experimental.go
- ext_editor_component.go
- ext_ui_context.go
- ext_ui_custom.go
- ext_ui_dialog_stack.go
- ext_ui_editor_snapshot.go
- ext_widgets.go
- extension_catalog_data.go
- extension_catalog_encoding.go
- extension_catalog_snapshot.go
- extension_conflicts.go
- extension_diagnostics.go
- extension_editor.go
- extension_host_info.go
- extension_model_operations.go
- extension_model_registry.go
- extension_package_warnings.go
- extension_session_graph.go
- extension_session_graph_models.go
- extension_session_read.go
- extension_session_replacement.go
- extension_settings_graph.go
- extension_trust_graph.go
- extension_ui_phase.go
- extensions.go
- external_editor.go
- external_editor_unix.go
- file_lock.go
- file_processor.go
- first_time_setup.go
- footer_data_provider.go
- git_watcher.go
- git_watcher_stamp_tim.go
- git_watcher_stamp_unix.go
- image_convert.go
- images.go
- initial_model.go
- install_change.go
- install_telemetry.go
- interactive.go
- interactive_api_key_login.go
- interactive_auth.go
- interactive_bug.go
- interactive_cache_warming.go
- interactive_changelog.go
- interactive_chat.go
- interactive_commands.go
- interactive_compaction.go
- interactive_crash.go
- interactive_easter_eggs.go
- interactive_editor.go
- interactive_events.go
- interactive_extension_errors.go
- interactive_extension_session_actions.go
- interactive_extensions.go
- interactive_frontend.go
- interactive_helpers.go
- interactive_hotkeys.go
- interactive_input.go
- interactive_input_preflight.go
- interactive_layout.go
- interactive_lifecycle.go
- interactive_login.go
- interactive_models.go
- interactive_native_login.go
- interactive_post_login.go
- interactive_queue_hint.go
- interactive_radius_mcp.go
- interactive_rebind.go
- interactive_reload.go
- interactive_run_prompt.go
- interactive_runtime.go
- interactive_scoped_models.go
- interactive_send_message.go
- interactive_settings_selector.go
- interactive_share.go
- interactive_signals_unix.go
- interactive_status.go
- interactive_terminal_reader.go
- interactive_theme.go
- interactive_theme_modal.go
- interactive_theme_watcher.go
- interactive_thinking.go
- interactive_thinking_runs.go
- interactive_tools_status.go
- interactive_transcript.go
- interactive_tree.go
- interactive_tui.go
- interactive_turn.go
- interactive_user_bash.go
- js_regexp_syntax.go
- key_id_schema.go
- keybindings.go
- keybindings_schema.go
- keys.go
- kit_conversation.go
- kitty_csi.go
- loaded_resources.go
- login_header.go
- mermaid_definition_parser.go
- mermaid_fence_parser.go
- mermaid_heading_parser.go
- mermaid_html_parser.go
- mermaid_raw.go
- mermaid_transform.go
- migrations.go
- model_availability.go
- model_cache_price.go
- model_catalog_data.go
- model_catalog_refresh.go
- model_command.go
- model_configured_auth_status.go
- model_data.go
- model_input_limits.go
- model_pattern.go
- model_picker.go
- model_refresh_background.go
- model_registry.go
- model_registry_runtime_models.go
- model_resolver.go
- model_runtime_members.go
- model_scope.go
- model_scope_line.go
- model_tasks.go
- model_typed_provider.go
- native_credential_operations.go
- native_model_runtime.go
- native_provider.go
- native_provider_composer.go
- native_provider_oauth.go
- native_selectors.go
- open_browser_unix.go
- output_guard.go
- owner_loop.go
- parity_harness.go
- paths.go
- pig_egg3d.go
- pig_logo_animation.go
- pig_logo_animation_play.go
- pig_logo_run.go
- presentation_theme.go
- presentation_tui.go
- program_status_reporter.go
- project_trust_warning.go
- prompt_diagnostics.go
- prompt_images.go
- prompt_templates.go
- provider_bridge.go
- provider_registration_namespace.go
- provider_registration_validation.go
- radius.go
- radius_composition.go
- radius_login_selector.go
- radius_models.go
- registry_request_auth.go
- reload_resources.go
- remote_catalog_provider.go
- remote_catalog_registry.go
- remote_editor.go
- request_auth_runtime.go
- resource_diagnostics.go
- resource_paths.go
- resource_source_info.go
- resources.go
- scoped_models_selection.go
- selfupdate.go
- selfupdate_configured.go
- selfupdate_lock.go
- selfupdate_package_command.go
- selfupdate_receipt.go
- selfupdate_signal_unix.go
- selfupdate_tier.go
- selfupdate_tier_unix.go
- session.go
- session_branch.go
- session_branch_preview.go
- session_branch_runtime.go
- session_context.go
- session_cwd.go
- session_export.go
- session_export_html.go
- session_file.go
- session_handle.go
- session_id_index.go
- session_import.go
- session_info_fast.go
- session_lazy.go
- session_listing.go
- session_manager.go
- session_manager_accessors.go
- session_manager_projection.go
- session_projection_calls.go
- session_restore.go
- session_resume.go
- session_selector.go
- session_selector_delete.go
- session_selector_delete_unix.go
- session_selector_load.go
- session_selector_status.go
- session_selectors.go
- session_share.go
- session_snapshot.go
- session_snapshot_linux.go
- session_snapshot_notwindows.go
- session_stats.go
- session_stats_scan.go
- session_store.go
- session_tree_index.go
- settings.go
- settings_compaction.go
- settings_default_tools.go
- settings_diagnostics.go
- settings_selector.go
- settings_submenu.go
- settings_wheel.go
- skills.go
- skills_loader.go
- slash_auth.go
- slash_bug.go
- slash_commands.go
- slash_helpers.go
- slash_session_handlers.go
- startup_header.go
- startup_hints.go
- startup_input.go
- startup_ui.go
- startup_visibility.go
- status_line.go
- stdin_buffer.go
- stored_credential.go
- subprocess_api_model.go
- suspend.go
- terminal_input_queue.go
- thinking_selector.go
- tmux_check.go
- tool_builtin_renderers.go
- tool_codemode_renderer.go
- tool_definition_renderers.go
- tool_details_object.go
- tool_render.go
- tool_render_list.go
- tool_render_shell.go
- tool_renderer_factory.go
- tool_result_content.go
- tree_row_format.go
- tree_selector.go
- trust_manager.go
- trust_selector.go
- uncaught_goroutine.go
- windows_self_update.go
- windows_self_update_other.go
- write_highlight_cache.go
- wsl.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Ports packages/coding-agent/src/core/compaction/branch-summarization.ts Branch summarization for tree navigation.
|
Ports packages/coding-agent/src/core/compaction/branch-summarization.ts Branch summarization for tree navigation. |
|
Package configschema renders the JSON Schema artifacts of Pi's configuration files (models.json, settings.json, keybindings.json and themes) from Go schema trees.
|
Package configschema renders the JSON Schema artifacts of Pi's configuration files (models.json, settings.json, keybindings.json and themes) from Go schema trees. |
|
Ports packages/coding-agent/src/core/export-html/ansi-to-html.ts
|
Ports packages/coding-agent/src/core/export-html/ansi-to-html.ts |
|
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. |
|
Package timings is the startup timing instrumentation Pi enables with PI_TIMING=1.
|
Package timings is the startup timing instrumentation Pi enables with PI_TIMING=1. |
|
tools/bash_executor.go: user bash execution (!cmd, RPC bash, SDK ExecuteBash).
|
tools/bash_executor.go: user bash execution (!cmd, RPC bash, SDK ExecuteBash). |