Documentation
¶
Overview ¶
Package coding is the public SDK for embedding the pig coding agent as a Go library.
Quick start ¶
import (
"context"
"github.com/MichaelKinsy/PiG/coding"
)
svcs, err := coding.CreateAgentSessionServices(coding.CreateAgentSessionServicesOptions{
CWD: "/my/project",
AgentDir: coding.DefaultAgentDir(),
})
if err != nil { return err }
defer svcs.Close()
rt, err := coding.NewRuntime(coding.RuntimeOptions{Services: svcs})
if err != nil { return err }
defer rt.Close()
model, err := coding.BuildModel("github-copilot/gpt-4o-mini", svcs)
if err != nil { return err }
sess, err := rt.New(coding.SessionStartOptions{
Model: model,
SystemPrompt: "You are a helpful coding assistant.",
})
if err != nil { return err }
defer sess.Close()
msgs, err := sess.Send(context.Background(), "What is 2+2?")
Architecture ¶
The package exposes three public types that compose into a working agent:
[Services]: dependency container. Owns the auth storage, model registry, settings manager. Construct once per process (or per CWD).
Runtime: session factory. Holds a Services plus an optional pre-loaded extension runner. Produces *Session values via New / Resume / Open / Continue.
Session: a single live conversation. Wraps the headless agent loop, the on-disk JSONL transcript, and the slash command registry. Exposes Send for prompts, Events for streaming, plus session-management methods (Fork, Clone, Tree, SetName).
Sessions persist as JSONL files at <CWD>/.pig/sessions/<id>.jsonl. Resuming a session via Runtime.Resume / Runtime.Continue rebuilds the agent's in-memory message history from the on-disk transcript.
Tools ¶
By default a fresh Session has the built-in coding-agent tools (read, write, bash, edit, grep, find, ls). Add your own tools via SessionStartOptions.ExtraTools: any type implementing agent.AgentTool works:
rt.New(coding.SessionStartOptions{
Model: model,
ExtraTools: []agent.AgentTool{myTool, otherTool},
})
To suppress all extension-supplied tools (e.g., for a sandboxed session), set SessionStartOptions.SkipExtensionTools = true.
Slash commands ¶
Sessions support the same slash commands as the interactive TUI via Session.DispatchSlash. In headless mode (no picker callbacks wired), commands like /resume / /fork / /tree fall back to text listings instead of overlay UIs:
out, err := sess.DispatchSlash("/tree")
for _, line := range out { fmt.Println(line) }
Forking and cloning ¶
Session.Fork moves the conversation leaf to an earlier entry; the next Send creates a new branch off that point. The agent's in-memory history is rebuilt to match.
Session.Clone snapshots the current path-to-leaf as a new JSONL file and returns a new Session that's independent of the source.
Streaming events ¶
Session.Events returns a buffered channel of agent.AgentEvent values. Subscribe BEFORE calling Send; events fire during the agent's tool-loop and include text deltas, tool calls, tool results, and end-of-turn markers:
go func() {
for ev := range sess.Events() {
switch ev.Type {
case agent.EventTextDelta:
fmt.Print(ev.TextDelta)
}
}
}()
See also ¶
- examples/sdk/main.go: minimal embedding example
- agent: agent loop + tool primitives
- ai: provider-agnostic LLM types and OAuth flows
Ports packages/coding-agent/src/core/model-runtime.ts
Services, Runtime, and Session form the public embedding API. Services owns shared configuration and credentials. Runtime creates and owns sessions. A Session owns one mutable conversation and its JSONL transcript.
This follows upstream Pi's AgentSessionServices, AgentSessionRuntime, and AgentSession responsibilities while using Go ownership and error semantics.
Ports packages/coding-agent/src/core/agent-session-runtime.ts
Ports importFromJsonl from packages/coding-agent/src/core/agent-session-runtime.ts.
Ports packages/coding-agent/src/core/agent-session.ts
UpstreamVersion, UpstreamPackageVersion and UpstreamCommit are the exact upstream Pi pin. The CLI, parity runner, source mirror, generated inventories, and Pig Porter consume them. The pin lives in .upstream/pin; `make pin-bump PI_UPSTREAM_REF=<tag|commit>` regenerates internal/coding/pigversion/pigversion.go and every other derived file, then the upgrade workflow in piglets/porter/skills/pig-porter/SKILL.md applies.
Index ¶
- Constants
- Variables
- func AcknowledgeEvent(event agent.AgentEvent) bool
- func BindExtensionHostSessionActions(bridge *subprocess.UIBridge, current func() *Session)
- func BindSessionExtensionActions(runner *inproc.Runner, bridge *subprocess.UIBridge, current func() *Session, ...)
- func BindSessionModelOperations(bridge *subprocess.UIBridge, session *Session, services *AgentSessionServices) func()
- func BindSessionReadActions(bridge *subprocess.UIBridge, current func() *Session, cwd, sessionDir string)
- func BridgeNewRunnerTools(rts []extension.RegisteredTool) ([]agent.AgentTool, []error)
- func BuildModel(spec string, svcs *AgentSessionServices) (*ai.Model, error)
- func BuildModelFromEntry(providerID, modelID string, entry icodingagent.ModelEntry, ...) (*ai.Model, error)
- func BuildNativeModel(registry *icodingagent.ModelRegistry, providerID, modelID string) *ai.Model
- func BuildUserContent(text string, images []ai.ImageContent) ai.UserContentBlocks
- func CreateEditToolDefinition(cwd string, options *tools.EditToolOptions) extension.ToolDefinition
- func CreateFindToolDefinition(cwd string, options *tools.FindToolOptions) extension.ToolDefinition
- func CreateGrepToolDefinition(cwd string, options *tools.GrepToolOptions) extension.ToolDefinition
- func CreateLsToolDefinition(cwd string, options *tools.LsToolOptions) extension.ToolDefinition
- func CreatePowerShellToolDefinition(cwd string, options *tools.PowerShellToolOptions) extension.ToolDefinition
- func CreateReadToolDefinition(cwd string, options *tools.ReadToolOptions) extension.ToolDefinition
- func CreateVirtualModel(definition VirtualModelDefinition) *ai.Model
- func CreateWriteToolDefinition(cwd string, options *tools.WriteToolOptions) extension.ToolDefinition
- func DefaultAgentDir() string
- func DefineTool(tool extension.ToolDefinition) extension.ToolDefinition
- func ExtensionHostSessionActions(current func() *Session, stage func() *ExtensionRunStage) (extension.ExtensionActions, extension.ContextActions)
- func ExtensionToolStartsActive(definition extension.ToolDefinition, allowed map[string]struct{}) bool
- func FindLatestResponse(messages []agent.AgentMessage) *agent.AssistantMessage
- func FindTurnStartIndex(entries []SessionEntry, entryIndex, startIndex int) int
- func GetLastAssistantUsage(entries []SessionEntry) *ai.Usage
- func GetVirtualModelState(branch []icodingagent.SessionEntry, provider, modelID string) json.RawMessage
- func IsVirtualAPI(api ai.API) bool
- func IsVirtualModel(model *ai.Model) bool
- func NewExtensionRunner(extensions []extension.Extension, runtime *extension.ExtensionRuntime, ...) *inproc.Runner
- func ReadStoredCredential(providerID string, authPath ...string) *ai.Credential
- func WatchHostState(bridge *subprocess.UIBridge, session *Session) func()
- func WatchSessionRunSignal(bridge *subprocess.UIBridge, session *Session) func()
- func WithCompactionYield(ctx context.Context, yield func(context.Context)) context.Context
- func WithForkSession(ctx context.Context, session *Session) context.Context
- func WrapRegisteredTool(registeredTool extension.RegisteredTool, runner *inproc.Runner) (agent.AgentTool, error)
- func WrapRegisteredTools(registeredTools []extension.RegisteredTool, runner *inproc.Runner) ([]agent.AgentTool, error)
- type AgentSessionEventListener
- type AgentSessionRuntimeDiagnostic
- type AgentSessionServices
- func (s *AgentSessionServices) AgentDir() string
- func (s *AgentSessionServices) ApplyExtensionFlagValues(extensions []extension.Extension) (map[string]any, []AgentSessionRuntimeDiagnostic)
- func (s *AgentSessionServices) Auth() *ai.AuthStorage
- func (s *AgentSessionServices) CWD() string
- func (s *AgentSessionServices) Close()
- func (s *AgentSessionServices) Credentials() ai.CredentialStore
- func (s *AgentSessionServices) Diagnostics() []AgentSessionRuntimeDiagnostic
- func (s *AgentSessionServices) ExtensionFlagValues() map[string]any
- func (s *AgentSessionServices) ModelRuntime() *ModelRuntime
- func (s *AgentSessionServices) Registry() *ModelRegistry
- func (s *AgentSessionServices) ResourceLoader() *DefaultResourceLoader
- func (s *AgentSessionServices) Settings() Settings
- func (s *AgentSessionServices) SettingsManager() *SettingsManager
- type AgentsFilesResult
- type BaseToolOverride
- type BashResult
- type BranchSummaryEntry
- type CacheWarmer
- type CompactionResult
- type CompactionSettings
- type CompatibilityRequestConfig
- type ContextFile
- type CreateAgentSessionFromServicesOptions
- type CreateAgentSessionOptions
- type CreateAgentSessionResult
- type CreateAgentSessionRuntimeFactory
- type CreateAgentSessionRuntimeOptions
- type CreateAgentSessionRuntimeResult
- type CreateAgentSessionServicesOptions
- type CreateModelRuntimeOptions
- type CredentialSynchronizationError
- type CredentialSynchronizationOperation
- type CutPointResult
- type DefaultResourceLoader
- func (l *DefaultResourceLoader) Close()
- func (l *DefaultResourceLoader) ExtendResources(paths ResourceExtensionPaths) error
- func (l *DefaultResourceLoader) GetAgentsFiles() AgentsFilesResult
- func (l *DefaultResourceLoader) GetAppendSystemPrompt() []string
- func (l *DefaultResourceLoader) GetAppendSystemPromptSources() []ResourceSource
- func (l *DefaultResourceLoader) GetExtensions() LoadExtensionsResult
- func (l *DefaultResourceLoader) GetPrompts() PromptsResult
- func (l *DefaultResourceLoader) GetSkills() SkillsResult
- func (l *DefaultResourceLoader) GetSystemPrompt() (string, bool)
- func (l *DefaultResourceLoader) GetSystemPromptSource() (ResourceSource, bool)
- func (l *DefaultResourceLoader) GetThemes() ThemesResult
- func (l *DefaultResourceLoader) LoadProjectTrustExtensions(ctx context.Context) (LoadExtensionsResult, error)
- func (l *DefaultResourceLoader) Reload(options ...ResourceLoaderReloadOptions) error
- func (l *DefaultResourceLoader) ReloadWith(ctx context.Context, options ...ResourceLoaderReloadOptions) error
- type DefaultResourceLoaderOptions
- type ExecuteBashOptions
- type ExportToHTMLOptions
- type ExtensionBindings
- type ExtensionFlagValue
- type ExtensionHost
- type ExtensionLoadError
- type ExtensionLoadRequest
- type ExtensionLoadWarning
- type ExtensionOAuthConfig
- type ExtensionResourcePath
- type ExtensionRunStage
- type ForkMessage
- type GraphModelRuntime
- func (g *GraphModelRuntime) Call(ctx context.Context, method string, raw json.RawMessage) (any, error)
- func (g *GraphModelRuntime) Release()
- func (g *GraphModelRuntime) Runtime() *ModelRuntime
- func (g *GraphModelRuntime) StreamModel(ctx context.Context, model map[string]any, request map[string]any) (*ai.AssistantMessageEventStream, error)
- type GraphPackageManager
- type GraphResourceLoader
- type LoadExtensionsResult
- type ModelCycleResult
- type ModelMutationOptions
- type ModelRegistry
- func (registry *ModelRegistry) Classify(ctx context.Context, model *ai.ClassifierModel, request ai.ClassifierContext, ...) ai.ClassifierResult
- func (registry *ModelRegistry) Complete(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessage
- func (registry *ModelRegistry) Find(provider, id string) *ai.Model
- func (registry *ModelRegistry) FindOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
- func (registry *ModelRegistry) GenerateImages(ctx context.Context, model *ai.ImageModel, request ai.ImagesContext, ...) ai.AssistantImages
- func (registry *ModelRegistry) GetAPIKeyAndHeaders(ctx context.Context, model *ai.Model) ResolvedRequestAuth
- func (registry *ModelRegistry) GetAPIKeyForProvider(ctx context.Context, id string) *string
- func (registry *ModelRegistry) GetAll() []*ai.Model
- func (registry *ModelRegistry) GetAvailable() []*ai.Model
- func (registry *ModelRegistry) GetAvailableOfType(ctx context.Context, modelType ai.ModelType, provider ...string) ([]ai.AnyModel, error)
- func (registry *ModelRegistry) GetError() string
- func (registry *ModelRegistry) GetModelOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
- func (registry *ModelRegistry) GetModelsOfType(modelType ai.ModelType, provider ...string) []ai.AnyModel
- func (registry *ModelRegistry) GetProviderAuth(ctx context.Context, id string) (*ai.AuthResult, error)
- func (registry *ModelRegistry) GetProviderAuthStatus(id string) ai.AuthStatus
- func (registry *ModelRegistry) HasConfiguredAuth(model *ai.Model) bool
- func (registry *ModelRegistry) IsUsingOAuth(model *ai.Model) bool
- func (registry *ModelRegistry) Refresh(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (registry *ModelRegistry) RegisterProvider(name string, config ProviderConfigInput) error
- func (registry *ModelRegistry) RegisterProviderObject(provider *ai.ModelsProvider) error
- func (registry *ModelRegistry) RegisterVirtualModel(definition VirtualModelDefinition) error
- func (registry *ModelRegistry) Stream(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (registry *ModelRegistry) StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (registry *ModelRegistry) UnregisterVirtualModel(provider, id string)
- type ModelRoute
- type ModelRouteReason
- type ModelRouteRequest
- type ModelRuntime
- func (runtime *ModelRuntime) CancelDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, ...) error
- func (runtime *ModelRuntime) CheckAuth(ctx context.Context, providerID string) (*ai.AuthCheck, error)
- func (runtime *ModelRuntime) Classify(ctx context.Context, model *ai.ClassifierModel, request ai.ClassifierContext, ...) ai.ClassifierResult
- func (runtime *ModelRuntime) Close()
- func (runtime *ModelRuntime) Complete(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessage
- func (runtime *ModelRuntime) CompleteSimple(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessage
- func (runtime *ModelRuntime) FetchDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, ...) *ai.AssistantMessage
- func (runtime *ModelRuntime) GenerateImages(ctx context.Context, model *ai.ImageModel, request ai.ImagesContext, ...) ai.AssistantImages
- func (runtime *ModelRuntime) GetAllAvailable(ctx context.Context, providerID ...string) ([]ai.AnyModel, error)
- func (runtime *ModelRuntime) GetAllModels(providerID ...string) []ai.AnyModel
- func (runtime *ModelRuntime) GetAuth(ctx context.Context, providerID string, ...) (*ai.AuthResult, error)
- func (runtime *ModelRuntime) GetAvailable(ctx context.Context, providerID ...string) ([]*ai.Model, error)
- func (runtime *ModelRuntime) GetAvailableOfType(ctx context.Context, modelType ai.ModelType, providerID ...string) ([]ai.AnyModel, error)
- func (runtime *ModelRuntime) GetAvailableSnapshot() []*ai.Model
- func (runtime *ModelRuntime) GetCompatibilityRequestConfig(model *ai.Model) (CompatibilityRequestConfig, error)
- func (runtime *ModelRuntime) GetError() string
- func (runtime *ModelRuntime) GetModel(providerID, modelID string) *ai.Model
- func (runtime *ModelRuntime) GetModelAuth(ctx context.Context, model ai.AnyModel, ...) (*ai.AuthResult, error)
- func (runtime *ModelRuntime) GetModelOfType(modelType ai.ModelType, providerID, modelID string) ai.AnyModel
- func (runtime *ModelRuntime) GetModels(providerID ...string) []*ai.Model
- func (runtime *ModelRuntime) GetModelsOfType(modelType ai.ModelType, providerID ...string) []ai.AnyModel
- func (runtime *ModelRuntime) GetPhysicalModel(provider, id string) *ai.Model
- func (runtime *ModelRuntime) GetProvider(id string) *ai.ModelsProvider
- func (runtime *ModelRuntime) GetProviderAuthStatus(providerID string) ai.AuthStatus
- func (runtime *ModelRuntime) GetProviders() []*ai.ModelsProvider
- func (runtime *ModelRuntime) GetRegisteredNativeProvider(providerID string) *ai.ModelsProvider
- func (runtime *ModelRuntime) GetRegisteredProviderConfig(providerID string) *ProviderConfigInput
- func (runtime *ModelRuntime) GetRegisteredProviderIds() []string
- func (runtime *ModelRuntime) HasConfiguredAuth(providerID string) bool
- func (runtime *ModelRuntime) IsUsingOAuth(providerID string) bool
- func (runtime *ModelRuntime) IsUsingSubscription(providerID string) bool
- func (runtime *ModelRuntime) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
- func (runtime *ModelRuntime) Login(ctx context.Context, id string, kind ai.AuthType, ...) (ai.Credential, error)
- func (runtime *ModelRuntime) Logout(ctx context.Context, id string) error
- func (runtime *ModelRuntime) Refresh(ctx context.Context, options ...ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (runtime *ModelRuntime) RegisterNativeProvider(provider *ai.ModelsProvider) error
- func (runtime *ModelRuntime) RegisterProvider(id string, input ProviderConfigInput) error
- func (runtime *ModelRuntime) RegisterVirtualModel(definition VirtualModelDefinition) error
- func (runtime *ModelRuntime) RemoveRuntimeApiKey(ctx context.Context, providerID string) error
- func (runtime *ModelRuntime) ResolveModel(ctx context.Context, model *ai.Model, messages []ai.Message, ...) (ModelRoute, error)
- func (runtime *ModelRuntime) RuntimeModels() []icodingagent.RuntimeModel
- func (runtime *ModelRuntime) SetChangeListener(listener func()) func()
- func (runtime *ModelRuntime) SetRuntimeApiKey(ctx context.Context, providerID, apiKey string) error
- func (runtime *ModelRuntime) Stream(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (runtime *ModelRuntime) StreamDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, ...) *ai.AssistantMessageEventStream
- func (runtime *ModelRuntime) StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (runtime *ModelRuntime) UnregisterProvider(providerID string)
- func (runtime *ModelRuntime) UnregisterVirtualModel(provider, id string)
- type ModelScopeDiagnostic
- type ModelSelection
- type NavigateTreeOptions
- type NavigateTreeResult
- type NestedCallRecorder
- func (r *NestedCallRecorder) AddUsage(usage ai.Usage)
- func (r *NestedCallRecorder) Finish(record *ai.NestedToolCallRecord, isError bool, errorText string)
- func (r *NestedCallRecorder) Snapshot() *ai.NestedToolCalls
- func (r *NestedCallRecorder) Start(toolCall agent.AgentToolCall) *ai.NestedToolCallRecord
- func (r *NestedCallRecorder) TotalUsage() *ai.Usage
- type NestedCallSummary
- type NestedToolCallHost
- type NestedToolCallOptions
- type NestedToolCallRunner
- type PreparedPrompt
- type PreparedPromptRun
- type PromptDisposition
- type PromptOptions
- type PromptTemplate
- type PromptsResult
- type ProviderConfigInput
- type QueueInputOptions
- type QueuedInputDisposition
- type QuietStartup
- type ReloadOption
- type ResolveCliModelOptions
- type ResolveCliModelResult
- type ResolveModelOptions
- type ResolveModelScopeResult
- type ResolveProjectTrustInput
- type ResolvedRequestAuth
- type ResourceExtensionPaths
- type ResourceLoader
- type ResourceLoaderReloadOptions
- type ResourceSource
- type RoutedModel
- type RunStart
- type Runtime
- func (rt *Runtime) CWD() string
- func (rt *Runtime) Close() error
- func (rt *Runtime) Continue(opts SessionStartOptions) (*Session, error)
- func (rt *Runtime) Diagnostics() []AgentSessionRuntimeDiagnostic
- func (rt *Runtime) EmitQuitShutdown()
- func (rt *Runtime) EmitQuitShutdownContext(ctx context.Context)
- func (rt *Runtime) ExtensionCommandActions(session *Session) extension.CommandActions
- func (rt *Runtime) ExtensionContext() *icodingagent.ExtensionContext
- func (rt *Runtime) Fork(ctx context.Context, entryID string, options *extension.ForkOptions) (RuntimeForkResult, error)
- func (rt *Runtime) ImportFromJsonl(ctx context.Context, input string, cwdOverride ...string) (extension.CancelledResult, error)
- func (rt *Runtime) ListSessions() ([]SessionInfo, error)
- func (rt *Runtime) ModelFallbackMessage() string
- func (rt *Runtime) New(opts SessionStartOptions) (*Session, error)
- func (rt *Runtime) NewExtensionRunner() *inproc.Runner
- func (rt *Runtime) NewSession(ctx context.Context, options *extension.NewSessionOptions) (extension.CancelledResult, error)
- func (rt *Runtime) Open(path string, opts SessionStartOptions) (*Session, error)
- func (rt *Runtime) Resume(id string, opts SessionStartOptions) (*Session, error)
- func (rt *Runtime) Services() *AgentSessionServices
- func (rt *Runtime) Session() *Session
- func (rt *Runtime) SetBeforeSessionInvalidate(fn func())
- func (rt *Runtime) SetBeforeSessionReplacement(drain func(context.Context) error)
- func (rt *Runtime) SetRebindSession(rebind func(context.Context, *Session) error)
- func (rt *Runtime) SetReload(reload func(context.Context, *Session) error)
- func (rt *Runtime) SwitchSession(ctx context.Context, path string, options ...*SwitchSessionOptions) (extension.CancelledResult, error)
- func (rt *Runtime) ValidateSwitchSession(path string) error
- type RuntimeForkResult
- type RuntimeOptions
- type ScopedModel
- type Session
- func (s *Session) Abort(ctx context.Context) error
- func (s *Session) AbortBash()
- func (s *Session) AbortBranchSummary()
- func (s *Session) AbortCompaction()
- func (s *Session) AbortRetry()
- func (s *Session) ActiveToolNames() []string
- func (s *Session) Agent() *agent.Agent
- func (s *Session) AgentRunAbortRequested() bool
- func (s *Session) AppendCustomEntry(customType string, data any) (string, error)
- func (s *Session) AutoCompactionEnabled() bool
- func (s *Session) AutoRetryEnabled() bool
- func (s *Session) AvailableModelSnapshot() []*ai.Model
- func (s *Session) AvailableThinkingLevels() []ai.ModelThinkingLevel
- func (s *Session) BeginModelChange(ctx context.Context, m *ai.Model, source extension.ModelSelectSource, ...) (func(), error)
- func (s *Session) BeginModelCycle(ctx context.Context, direction string, options ...ModelMutationOptions) (*ModelCycleResult, func(), error)
- func (s *Session) BeginModelCycleOnMain(ctx context.Context, direction string, options ModelMutationOptions) (*ModelCycleResult, func(), error)
- func (s *Session) BeginPreparedPrompt(ctx context.Context, start *RunStart, p *PreparedPrompt) (*PreparedPromptRun, error)
- func (s *Session) BeginPromptCompactionCheck(ctx context.Context) (due func(context.Context) error, ok bool, err error)
- func (s *Session) BeginRunStart() (*RunStart, error)
- func (s *Session) BindExtensions(ctx context.Context, bindings ExtensionBindings) error
- func (s *Session) CWD() string
- func (s *Session) CacheWarmingStatus() *icodingagent.CacheWarmingStatus
- func (s *Session) CallableToolNames() []string
- func (s *Session) CheckModelAuth(m *ai.Model) error
- func (s *Session) CheckPromptCompaction(ctx context.Context) error
- func (s *Session) ClearQueue() (steering, followUp []string)
- func (s *Session) Clone() (*Session, error)
- func (s *Session) CloneInPlace() error
- func (s *Session) Close() error
- func (s *Session) Compact(ctx context.Context, customInstructions string) (*CompactionResult, error)
- func (s *Session) CompactForExtension(ctx context.Context, customInstructions string) (extension.CompactionResult, error)
- func (s *Session) ContextUsage() *SessionContextUsage
- func (s *Session) CreateReplacedSessionContext(ctx context.Context) *extension.ReplacedSessionContext
- func (s *Session) CycleModel(direction string, options ...ModelMutationOptions) (*ModelCycleResult, error)
- func (s *Session) CycleThinkingLevel(options ...ModelMutationOptions) (ai.ModelThinkingLevel, error)
- func (s *Session) DeferCustomMessage(message agent.AgentMessage) bool
- func (s *Session) DiscardAddedDefaultTools()
- func (s *Session) DiscardEvents()
- func (s *Session) DispatchSlash(line string) ([]string, error)
- func (s *Session) Dispose()
- func (s *Session) EmitSessionShutdown(reason string)
- func (s *Session) EmitSessionShutdownTransition(reason, targetSessionFile string)
- func (s *Session) EmitSessionStart(reason string) error
- func (s *Session) EmitSessionStartTransition(reason, previousSessionFile string) error
- func (s *Session) Entries() []icodingagent.SessionEntry
- func (s *Session) Events() <-chan agent.AgentEvent
- func (s *Session) ExecuteBash(ctx context.Context, command string, onChunk func(string), ...) (BashResult, error)
- func (s *Session) ExportToHTML(outputPath string, options ...ExportToHTMLOptions) (string, error)
- func (s *Session) ExportToJsonl(outputPath string) (string, error)
- func (s *Session) ExtensionCommandActions() extension.CommandActions
- func (s *Session) ExtensionCompact(options *extension.CompactOptions)
- func (s *Session) ExtensionHost() ExtensionHost
- func (s *Session) ExtensionRunner() *inproc.Runner
- func (s *Session) ExtensionSetModel(ctx context.Context, model *ai.Model) (bool, error)
- func (s *Session) ExtensionUserMessageRunPending() bool
- func (s *Session) FlushDeferredCustomMessages() error
- func (s *Session) FlushEvents(ctx context.Context) error
- func (s *Session) FollowUp(ctx context.Context, text string, images []ai.ImageContent, ...) (QueuedInputDisposition, error)
- func (s *Session) FollowUpMode() agent.QueueMode
- func (s *Session) Fork(entryID string) error
- func (s *Session) ForkToNewSession(userMsgEntryID string) error
- func (s *Session) ForkToNewSessionWithText(userMsgEntryID string) (string, error)
- func (s *Session) GetAllTools() []extension.ToolInfo
- func (s *Session) GetFollowUpMessages() []string
- func (s *Session) GetSessionStats() SessionStats
- func (s *Session) GetSteeringMessages() []string
- func (s *Session) GetSystemPromptOptions() *extension.BuildSystemPromptOptions
- func (s *Session) GetToolDefinition(name string) (extension.ToolDefinition, bool)
- func (s *Session) HasDeferredCustomMessages() bool
- func (s *Session) HasExtensionHandlers(eventType string) bool
- func (s *Session) HasPendingBashMessages() bool
- func (s *Session) HasPendingMessages() bool
- func (s *Session) HiddenDeclarationNames() []string
- func (s *Session) HiddenDeclarations() map[string]struct{}
- func (s *Session) HoldAgentEvents() (release func())
- func (s *Session) ID() string
- func (s *Session) ImportFromJsonl(ctx context.Context, inputPath, cwdOverride string) (extension.CancelledResult, error)
- func (s *Session) Inner() *icodingagent.Session
- func (s *Session) IsBashRunning() bool
- func (s *Session) IsCompacting() bool
- func (s *Session) IsIdle() bool
- func (s *Session) IsRetrying() bool
- func (s *Session) IsStreaming() bool
- func (s *Session) LastAssistantText() *string
- func (s *Session) LeafID() *string
- func (s *Session) ListSessions() ([]SessionInfo, error)
- func (s *Session) Messages() []agent.AgentMessage
- func (s *Session) Model() *ai.Model
- func (s *Session) ModelRegistry() *ModelRegistry
- func (s *Session) ModelRuntime() *ModelRuntime
- func (s *Session) NavigateTree(ctx context.Context, targetID string, opts NavigateTreeOptions) (NavigateTreeResult, error)
- func (s *Session) NavigateTreeHandle(ctx context.Context, targetID string, options icodingagent.NavigateTreeOptions) (icodingagent.NavigateTreeResult, error)
- func (s *Session) NewSession(parentSession string) error
- func (s *Session) ObserveReplicatedState(observe func()) func()
- func (s *Session) OnAgentSettled()
- func (s *Session) Path() string
- func (s *Session) PendingMessageCount() int
- func (s *Session) PreparePrompt(ctx context.Context, content []ai.UserContentBlock) (*PreparedPrompt, error)
- func (s *Session) Prompt(ctx context.Context, text string, options ...*PromptOptions) error
- func (s *Session) PromptTemplates() []PromptTemplate
- func (s *Session) QueueAgentStartMessages(messages []extension.CustomMessageRef)
- func (s *Session) QueueFollowUp(text string, images []ai.ImageContent)
- func (s *Session) QueueSteer(text string, images []ai.ImageContent)
- func (s *Session) ReapplyActiveTools(names []string)
- func (s *Session) RecordBashResult(command string, result BashResult, excludeFromContext *bool) error
- func (s *Session) RecordUserBashResult(command string, result icodingagent.BashResult, excludeFromContext bool) error
- func (s *Session) RefreshContext()
- func (s *Session) RefreshTools() error
- func (s *Session) RefreshToolsAfterReload() error
- func (s *Session) Reload(ctx context.Context, options ...ReloadOption) error
- func (s *Session) ReloadExtensions(extensions []extension.Extension, runtime ...*extension.ExtensionRuntime) (*inproc.Runner, error)
- func (s *Session) ReloadSettings()
- func (s *Session) ReplaceInner(sess *icodingagent.Session)
- func (s *Session) ReplaceRunner(runner *inproc.Runner)
- func (s *Session) RequestAbort()
- func (s *Session) ResourceLoader() ResourceLoader
- func (s *Session) RetryAttempt() int
- func (s *Session) RoutedModel() *RoutedModel
- func (s *Session) RoutedModelSelection() *icodingagent.RoutedModelSelection
- func (s *Session) RunAgentPrompt(ctx context.Context, start func(context.Context) ([]agent.AgentMessage, error)) ([]agent.AgentMessage, error)
- func (s *Session) RunInputHandlers(ctx context.Context, text string, images []ai.ImageContent, ...) (string, []ai.ImageContent, bool, error)
- func (s *Session) ScopedModels() []ScopedModel
- func (s *Session) Send(ctx context.Context, prompt string) ([]agent.AgentMessage, error)
- func (s *Session) SendContent(ctx context.Context, content []ai.UserContentBlock) ([]agent.AgentMessage, error)
- func (s *Session) SendContentWithPreflight(ctx context.Context, content []ai.UserContentBlock, preflight func()) ([]agent.AgentMessage, error)
- func (s *Session) SendCustomMessage(ctx context.Context, message extension.CustomMessageRef, ...) error
- func (s *Session) SendExtensionUserMessage(content any, options *extension.SendUserMessageOptions) error
- func (s *Session) SendExtensionUserMessageStaged(content any, options *extension.SendUserMessageOptions, ...) error
- func (s *Session) SendMessage(message extension.CustomMessageRef, options *extension.SendMessageOptions) error
- func (s *Session) SendMessageStaged(message extension.CustomMessageRef, options *extension.SendMessageOptions, ...) error
- func (s *Session) SendUserMessage(ctx context.Context, content any, options *extension.SendUserMessageOptions) error
- func (s *Session) Services() *AgentSessionServices
- func (s *Session) SessionManager() *SessionManager
- func (s *Session) SessionName() string
- func (s *Session) SetActiveToolsByName(names []string)
- func (s *Session) SetAutoCompactionEnabled(enabled bool)
- func (s *Session) SetAutoRetryEnabled(enabled bool)
- func (s *Session) SetBeforeSessionReplacement(drain func(context.Context) error)
- func (s *Session) SetCacheWarmingMode(mode icodingagent.CacheWarmingMode) error
- func (s *Session) SetFollowUpMode(mode agent.QueueMode) error
- func (s *Session) SetModel(m *ai.Model, options ...ModelMutationOptions) error
- func (s *Session) SetModelOnMain(ctx context.Context, m *ai.Model, options ModelMutationOptions, ...) error
- func (s *Session) SetName(name string) error
- func (s *Session) SetPromptResources(templates []PromptTemplate, skills []*Skill)
- func (s *Session) SetRebindSession(rebind func(context.Context, extension.SessionStartEvent) error)
- func (s *Session) SetRetryContinuationScheduler(schedule func(func()))
- func (s *Session) SetRunPrompt(run *icodingagent.BeforeAgentStartRun)
- func (s *Session) SetScopedModels(models []ScopedModel)
- func (s *Session) SetSessionName(name string) error
- func (s *Session) SetSteeringMode(mode agent.QueueMode) error
- func (s *Session) SetSystemPromptResources(resources SystemPromptResources)
- func (s *Session) SetSystemPromptSections(sections ai.OrderedSections)
- func (s *Session) SetThinkingLevel(level ai.ModelThinkingLevel, options ...ModelMutationOptions) error
- func (s *Session) SetThinkingLevelOnMain(level ai.ModelThinkingLevel, options ModelMutationOptions, ...) error
- func (s *Session) SettingsManager() *icodingagent.SettingsManager
- func (s *Session) Signal() context.Context
- func (s *Session) SlashCommands() []extension.SlashCommandInfo
- func (s *Session) SlashCommandsFor(runner *inproc.Runner) []extension.SlashCommandInfo
- func (s *Session) StartEvent() extension.SessionStartEvent
- func (s *Session) State() agent.AgentState
- func (s *Session) Steer(ctx context.Context, text string, images []ai.ImageContent, ...) (QueuedInputDisposition, error)
- func (s *Session) SteeringMode() agent.QueueMode
- func (s *Session) StreamModel(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (s *Session) Subscribe(listener AgentSessionEventListener) func()
- func (s *Session) SummarizeForBugReport(ctx context.Context, hint string) (string, error)
- func (s *Session) SupportsThinking() bool
- func (s *Session) SwitchSession(path string) error
- func (s *Session) SystemPrompt() string
- func (s *Session) ThinkingLevel() ai.ModelThinkingLevel
- func (s *Session) ToolActions() extension.ToolActions
- func (s *Session) Tools() []agent.AgentTool
- func (s *Session) Tree() *icodingagent.SessionTreeNode
- func (s *Session) UserMessagesForForking() []ForkMessage
- func (s *Session) ValidateFork(entryID, position string) error
- func (s *Session) ValidatePromptModelAuth(ctx context.Context) error
- func (s *Session) WaitForIdle(ctx context.Context) error
- type SessionContextUsage
- type SessionEntry
- type SessionGraph
- type SessionImportFileNotFoundError
- type SessionInfo
- type SessionManager
- type SessionOptions
- type SessionStartOptions
- type SessionStats
- type SessionStatsTokens
- type SessionTreeNode
- type Settings
- type SettingsManager
- type Skill
- type SkillsResult
- type SlashContextHandle
- type SwitchSessionOptions
- type SystemPromptResources
- type ThemesResult
- type TreePreparation
- type VirtualModelDefinition
- type VirtualModelStateData
Constants ¶
const ( CredentialSynchronizationLogin = icodingagent.CredentialSynchronizationLogin CredentialSynchronizationLogout = icodingagent.CredentialSynchronizationLogout CredentialSynchronizationSetRuntimeAPIKey = icodingagent.CredentialSynchronizationSetRuntimeAPIKey CredentialSynchronizationRemoveRuntimeAPIKey = icodingagent.CredentialSynchronizationRemoveRuntimeAPIKey )
const ( QuietStartupFalse = icodingagent.QuietStartupFalse QuietStartupTrue = icodingagent.QuietStartupTrue QuietStartupHeader = icodingagent.QuietStartupHeader )
Quiet startup values.
const ( DispositionHandled QueuedInputDisposition = "handled" DispositionQueued QueuedInputDisposition = "queued" DispositionStarted PromptDisposition = "started" )
The dispositions of upstream's PromptDisposition union.
const ( ModelRouteReasonUser = extension.ModelRouteReasonUser ModelRouteReasonContinuation = extension.ModelRouteReasonContinuation ModelRouteReasonRetry = extension.ModelRouteReasonRetry ModelRouteReasonDirect = extension.ModelRouteReasonDirect )
The reasons of upstream's ModelRouteReason union.
const PigVersion = pigversion.PigVersion
PigVersion is PiG's release line. It advances independently of the upstream Pi target.
const UpstreamCommit = pigversion.UpstreamCommit
UpstreamCommit is the exact Pi commit of the pin.
const UpstreamPackageVersion = pigversion.UpstreamPackageVersion
UpstreamPackageVersion is the version Pi's package.json files and `pi --version` report. It equals UpstreamVersion for a release tag.
const UpstreamRef = pigversion.UpstreamRef
UpstreamRef is the pinned tag or commit of Pi.
const UpstreamReviewedVersion = "0.84.0"
UpstreamReviewedVersion is the most recent pin whose parity ledgers carry reviewed dispositions. Leap ledgers (the semantic interface delta, the behavior-input mapping carry-forward, and the upstream-sync manifest) cover every change from this version to UpstreamVersion. Advance it only after those ledgers have no pending rows.
const UpstreamVersion = pigversion.UpstreamVersion
UpstreamVersion is the pinned Pi build's display and ledger version: the release version for a tag, the release version plus +<commit[:8]> for a commit (Pi 1.1.0+42a3497d). Ledger files and parity inventories are named by it.
const Version = pigversion.Version
Version is PiG's one displayed version: its own release line with the Pi release it ports as semver build metadata (for example 0.2.0+0.87.1). Semver precedence ignores build metadata, so Version sorts exactly as PigVersion. Self-update comparisons, release tags, and the Piglet compatibility check still use PigVersion itself.
const VirtualModelAPI = extension.VirtualModelAPI
VirtualModelAPI is the API id of virtual catalog entries. upstream: virtual-models.ts:29 (VIRTUAL_MODEL_API)
const VirtualModelStateEntry = extension.VirtualModelStateEntry
VirtualModelStateEntry is the custom entry type that stores router state on the session branch. upstream: virtual-models.ts:32 (VIRTUAL_MODEL_STATE_ENTRY)
Variables ¶
var DefaultCompactionSettings = compaction.DefaultCompactionSettings
DefaultCompactionSettings is upstream DEFAULT_COMPACTION_SETTINGS.
var ErrNoServices = errors.New("coding: nil Services")
ErrNoServices is returned by APIs that require a Services instance when the caller passed nil.
var ErrSessionNotReady = errors.New("agent session not initialized")
ErrSessionNotReady rejects a session action that an extension calls before the Session exists.
var NestedCallLimits = struct { MaxCalls int MaxArgumentBytesPerCall int MaxArgumentBytesTotal int MaxErrorChars int }{MaxCalls: 256, MaxArgumentBytesPerCall: 8 * 1024, MaxArgumentBytesTotal: 32 * 1024, MaxErrorChars: 500}
NestedCallLimits are the limits of the nested-call record on a tool result: arguments over the per-call or total size are omitted, calls beyond the count are dropped, and the record is marked incomplete when any of that happens.
upstream: nested-tool-calls.ts:26-31 (NESTED_CALL_LIMITS)
Functions ¶
func AcknowledgeEvent ¶
func AcknowledgeEvent(event agent.AgentEvent) bool
AcknowledgeEvent handles the internal marker used by FlushEvents. An Events consumer calls this after writing earlier events and does not serialize a marker when this returns true.
func BindExtensionHostSessionActions ¶
func BindExtensionHostSessionActions(bridge *subprocess.UIBridge, current func() *Session)
BindExtensionHostSessionActions binds the subprocess host actions that Pi's _bindExtensionCore binds to the Session in every mode: getActiveTools and setActiveTools (getActiveToolNames, setActiveToolsByName) and sendMessage (agent-session.ts:3341-3352). current returns the Session the actions reach, or nil before it exists: getActiveTools then lists no tools, setActiveTools does nothing and sendMessage fails with ErrSessionNotReady.
func BindSessionExtensionActions ¶
func BindSessionExtensionActions(runner *inproc.Runner, bridge *subprocess.UIBridge, current func() *Session, contextActions extension.ContextActions, stage func() *ExtensionRunStage, replacement ...func(*Session) extension.CommandActions)
BindSessionExtensionActions binds the session-backed actions for in-process extensions (runner) and subprocess extensions (bridge host actions). contextActions carries the mode's other context actions, including the extension flag values supplied before session_start.
stage, when non-nil, places the runs that sendUserMessage and sendMessage start (ExtensionHostSessionActions); in-process and subprocess extensions share it.
replacement optionally supplies the command actions of a Session, so a mode that owns a Runtime routes newSession, fork and switchSession through it. Without it the Session's own actions apply.
func BindSessionModelOperations ¶
func BindSessionModelOperations(bridge *subprocess.UIBridge, session *Session, services *AgentSessionServices) func()
BindSessionModelOperations binds the model operations of session (its model, the model runtime's catalog, setModel and the image and classify calls) to the subprocess extensions of bridge. The returned function unbinds them.
func BindSessionReadActions ¶
func BindSessionReadActions(bridge *subprocess.UIBridge, current func() *Session, cwd, sessionDir string)
BindSessionReadActions binds the session manager reads subprocess extensions make, for print, JSON and RPC mode. Upstream hands every mode's extensions the session's SessionManager (runner.ts createContext sessionManager). cwd and sessionDir are the session manager's own.
func BridgeNewRunnerTools ¶
func BridgeNewRunnerTools(rts []extension.RegisteredTool) ([]agent.AgentTool, []error)
BridgeNewRunnerTools converts extension-registered tools into AgentTools suitable for the agent loop. Preserves registration order. Tools whose schema fails to parse are skipped with a returned diagnostics slice.
func BuildModel ¶
func BuildModel(spec string, svcs *AgentSessionServices) (*ai.Model, error)
BuildModel constructs an *ai.Model from a "provider/model" spec string, using the given Services for auth and registry lookup. The test-faux backend reuses one provider per Services container so tool-call counters survive request preparation.
Recognised provider prefixes:
- "github-copilot/<model>" : uses the OAuth token in auth.json
- "openai/<model>" : OPENAI_API_KEY (or registry override)
- "openrouter/<model>" : OPENROUTER_API_KEY
- "groq/<model>" : GROQ_API_KEY
- "ollama/<model>" : OLLAMA_HOST or http://localhost:11434/v1
- any other "<id>/<model>" : treated as OpenAI-compatible; API key from <ID_UPPER>_API_KEY env var
A bare "<model>" with no slash is interpreted as "openai/<model>" for backward compatibility with environments that hardcode OpenAI.
The catalog (context window, cost, capabilities) is resolved via ai.LookupModel; if the spec isn't in the codegen registry, the returned Model still works but has empty cost/window data (status-line just shows blank context %).
Library consumers can use this to construct models without hand-rolling provider switching:
svcs, _ := coding.CreateAgentSessionServices(...)
defer svcs.Close()
model, _ := coding.BuildModel("github-copilot/gpt-4o-mini", svcs)
rt, _ := coding.NewRuntime(coding.RuntimeOptions{Services: svcs})
sess, _ := rt.New(coding.SessionStartOptions{Model: model})
func BuildModelFromEntry ¶
func BuildModelFromEntry(providerID, modelID string, entry icodingagent.ModelEntry, svcs *AgentSessionServices) (*ai.Model, error)
BuildModelFromEntry constructs the Model for an already-resolved entry. The CLI model resolver resolves the entry itself (catalog match, models.json, or the provider's default-model fallback) and shares this construction with BuildModel, so both paths branch on the API kind and carry the catalog base URL and credentials the same way.
func BuildNativeModel ¶
func BuildNativeModel(registry *icodingagent.ModelRegistry, providerID, modelID string) *ai.Model
BuildNativeModel binds a registered model to the same authenticated native callback path used by ModelRuntime. The CLI's model selection uses this too.
func BuildUserContent ¶
func BuildUserContent(text string, images []ai.ImageContent) ai.UserContentBlocks
BuildUserContent constructs the upstream user-content block list: a leading text block, including empty text, followed by any image attachments.
func CreateEditToolDefinition ¶
func CreateEditToolDefinition(cwd string, options *tools.EditToolOptions) extension.ToolDefinition
CreateEditToolDefinition is upstream's createEditToolDefinition (edit.ts:143).
func CreateFindToolDefinition ¶
func CreateFindToolDefinition(cwd string, options *tools.FindToolOptions) extension.ToolDefinition
CreateFindToolDefinition is upstream's createFindToolDefinition (find.ts:70).
func CreateGrepToolDefinition ¶
func CreateGrepToolDefinition(cwd string, options *tools.GrepToolOptions) extension.ToolDefinition
CreateGrepToolDefinition is upstream's createGrepToolDefinition (grep.ts:70).
func CreateLsToolDefinition ¶
func CreateLsToolDefinition(cwd string, options *tools.LsToolOptions) extension.ToolDefinition
CreateLsToolDefinition is upstream's createLsToolDefinition (ls.ts:54).
func CreatePowerShellToolDefinition ¶
func CreatePowerShellToolDefinition(cwd string, options *tools.PowerShellToolOptions) extension.ToolDefinition
CreatePowerShellToolDefinition is upstream's createPowerShellToolDefinition (powershell.ts:49).
func CreateReadToolDefinition ¶
func CreateReadToolDefinition(cwd string, options *tools.ReadToolOptions) extension.ToolDefinition
CreateReadToolDefinition is upstream's createReadToolDefinition (read.ts:86).
func CreateVirtualModel ¶
func CreateVirtualModel(definition VirtualModelDefinition) *ai.Model
CreateVirtualModel builds the catalog entry of a virtual model.
upstream: virtual-models.ts:159-176 (createVirtualModel)
func CreateWriteToolDefinition ¶
func CreateWriteToolDefinition(cwd string, options *tools.WriteToolOptions) extension.ToolDefinition
CreateWriteToolDefinition is upstream's createWriteToolDefinition (write.ts:44).
func DefaultAgentDir ¶
func DefaultAgentDir() string
DefaultAgentDir is Pi's getAgentDir: the global agent config directory the pig binary uses. PIG_CODING_AGENT_DIR (PI_CODING_AGENT_DIR when PIG_USE_PI_DIRS=1) names it with a leading tilde expanded; otherwise it is $PIG_HOME/agent if PIG_HOME is set, else ~/.pig/agent.
func DefineTool ¶
func DefineTool(tool extension.ToolDefinition) extension.ToolDefinition
DefineTool returns the tool definition it is given, as Pi's `defineTool` (packages/coding-agent/src/core/extensions/types.ts:676) does. Pi uses it to preserve TypeScript's contextual inference of a tool's parameters; Go's definition is one concrete type, so the function adds only the call shape a ported extension writes.
Ports packages/coding-agent/src/core/extensions/types.ts defineTool.
func ExtensionHostSessionActions ¶
func ExtensionHostSessionActions(current func() *Session, stage func() *ExtensionRunStage) (extension.ExtensionActions, extension.ContextActions)
ExtensionHostSessionActions is the Session-owned messages, names, and context actions in every mode. The current getter supplies the live Session, or nil while it is being created. stage, when non-nil, returns the stage of a run an extension sends at that moment, or nil to start it as the Session does.
func ExtensionToolStartsActive ¶
func ExtensionToolStartsActive(definition extension.ToolDefinition, allowed map[string]struct{}) bool
ExtensionToolStartsActive reports whether an extension tool is active when a Session starts. With an allowlist (`--tools`, `--no-tools`), naming a declarable tool activates it even when it is not active by default; without one, only a tool that activates on registration is active.
upstream: agent-session.ts:3487-3506 (_refreshToolRegistry)
func FindLatestResponse ¶
func FindLatestResponse(messages []agent.AgentMessage) *agent.AssistantMessage
FindLatestResponse returns the latest successful response. Its model is physical: failed or aborted requests, including failed routing, are skipped.
upstream: virtual-models.ts:110-118 (findLatestResponse)
func FindTurnStartIndex ¶
func FindTurnStartIndex(entries []SessionEntry, entryIndex, startIndex int) int
FindTurnStartIndex is upstream findTurnStartIndex: the index of the user-role entry that starts the turn containing entryIndex, or -1.
func GetLastAssistantUsage ¶
func GetLastAssistantUsage(entries []SessionEntry) *ai.Usage
GetLastAssistantUsage is upstream getLastAssistantUsage: the usage of the last assistant message that reports one, or nil.
func GetVirtualModelState ¶
func GetVirtualModelState(branch []icodingagent.SessionEntry, provider, modelID string) json.RawMessage
GetVirtualModelState returns the latest router state a session branch stores for a virtual model, or nil.
upstream: virtual-models.ts:148-156 (getVirtualModelState)
func IsVirtualAPI ¶
IsVirtualAPI reports whether an API id is VirtualModelAPI.
upstream: virtual-models.ts:105-107 (isVirtualModel, over a message)
func IsVirtualModel ¶
IsVirtualModel reports whether a model names a virtual model. Failed routing leaves the virtual model on its message, so a message's API is checked the same way with IsVirtualAPI.
upstream: virtual-models.ts:105-107 (isVirtualModel)
func NewExtensionRunner ¶
func NewExtensionRunner(extensions []extension.Extension, runtime *extension.ExtensionRuntime, cwd string, sessionManager *SessionManager, modelRegistry extension.ModelRegistry) *inproc.Runner
NewExtensionRunner is Pi's ExtensionRunner constructor (extensions, runtime, cwd, sessionManager, modelRegistry): the runner over the loader's extensions and its shared runtime, with the SessionManager ctx.sessionManager exposes and the registry ctx.modelRegistry reads. A nil runtime gives it a fresh one; a nil sessionManager or registry waits for the binding that supplies it.
upstream: runner.ts:395-408 (constructor)
func ReadStoredCredential ¶
func ReadStoredCredential(providerID string, authPath ...string) *ai.Credential
ReadStoredCredential is a one-off synchronous read of providerID's credential from an auth.json file, without instantiating a store or resolving configured key values (auth-storage.ts:496). authPath defaults to the agent directory's auth.json. It returns nil, as upstream returns undefined, for a missing or malformed file or an absent entry. An entry that is not a credential object is also nil: upstream hands back whatever JSON the file holds there, which its Credential type does not admit.
func WatchHostState ¶
func WatchHostState(bridge *subprocess.UIBridge, session *Session) func()
WatchHostState reports each change of the host state the extension runtimes replicate and no extension call announces (the Session's model, thinking level and session name, the settings, and the active theme) to the extension host, and returns the function that stops. Pi's `ctx.model`, `pi.getSettings()`, `pi.getSessionName()` and `ctx.ui.theme` read the live Session, settings and global theme (runner.ts:906, loader.ts:411-414, interactive-mode.ts:2665), so a runtime that reads between two requests must learn of a change when it happens, not at its next request.
func WatchSessionRunSignal ¶
func WatchSessionRunSignal(bridge *subprocess.UIBridge, session *Session) func()
WatchSessionRunSignal reports each run the Session's agent begins or ends to the extension host, and returns the function that stops. Pi's ctx.signal is `() => this.agent.signal` (agent-session.ts:3368), read live by the extension that holds ctx, so every runtime must learn of a run change when it happens, not at its next request.
func WithCompactionYield ¶
WithCompactionYield returns ctx carrying yield, which a manual compaction calls with its own context after its synchronous checks and before its first await (session_before_compact or the summary request auth). A mode uses it to let work that Pi runs while the compaction awaits, such as a replacement's teardown, act first.
func WithForkSession ¶
WithForkSession makes a fork started with the returned context read its entry, and the Session file it branches, from session instead of the Runtime's current Session. An RPC input batch that requests a fork while an earlier replacement of the batch is still pending forks the Session that was current when the fork was requested, as Pi's does.
func WrapRegisteredTool ¶
func WrapRegisteredTool(registeredTool extension.RegisteredTool, runner *inproc.Runner) (agent.AgentTool, error)
WrapRegisteredTool wraps a registered tool into an AgentTool whose every call gets runner's tool context for its call id, as wrapper.ts wrapRegisteredTool does through wrapToolDefinition. A schema that fails to parse is an error.
func WrapRegisteredTools ¶
func WrapRegisteredTools(registeredTools []extension.RegisteredTool, runner *inproc.Runner) ([]agent.AgentTool, error)
WrapRegisteredTools wraps every registered tool in order (wrapper.ts wrapRegisteredTools); the first tool that cannot be wrapped fails the call.
Types ¶
type AgentSessionEventListener ¶
type AgentSessionEventListener func(agent.AgentEvent)
AgentSessionEventListener is a Session event listener (agent-session.ts:240 `(event: AgentSessionEvent) => void`).
type AgentSessionRuntimeDiagnostic ¶
type AgentSessionRuntimeDiagnostic = icodingagent.AgentSessionRuntimeDiagnostic
AgentSessionRuntimeDiagnostic is a startup problem found while creating Services (upstream AgentSessionRuntimeDiagnostic).
type AgentSessionServices ¶
type AgentSessionServices struct {
// contains filtered or unexported fields
}
Services is the lowest-level dependency container: auth storage, settings manager, and model registry. One Services instance is typically constructed per-process and shared by every Runtime/Session.
Services is intentionally narrow. Anything that needs the auth file path, the merged settings, or model lookup goes through this type. Anything specific to a single conversation (history, tools, hooks) belongs on Session, not Services.
func CreateAgentSessionServices ¶
func CreateAgentSessionServices(opts CreateAgentSessionServicesOptions) (*AgentSessionServices, error)
CreateAgentSessionServices constructs a Services container. Failure modes:
- cannot resolve CWD when none provided → wrapped os.Getwd error
- auth.json directory cannot be created/read → wrapped error
Settings and registry constructors never fail; they fall back to defaults if their backing files are missing or malformed. The caller owns Services.Close; a Runtime or Session supplied with these Services does not close them.
func (*AgentSessionServices) AgentDir ¶
func (s *AgentSessionServices) AgentDir() string
AgentDir returns the global agent config directory (typically ~/.pig/agent or $PIG_HOME/agent).
func (*AgentSessionServices) ApplyExtensionFlagValues ¶
func (s *AgentSessionServices) ApplyExtensionFlagValues(extensions []extension.Extension) (map[string]any, []AgentSessionRuntimeDiagnostic)
ApplyExtensionFlagValues checks ServicesOptions.ExtensionFlagValues against the flags the loaded extensions registered and returns the values that extensions read. A boolean flag is true whatever the value; a string flag takes its string value, and a non-string value is an error ("requires a value"); a name no extension registered is reported with the other unknown names in one "Unknown option" error. The diagnostics are also appended to [Services.Diagnostics]. Ports packages/coding-agent/src/core/agent-session-services.ts applyExtensionFlagValues.
func (*AgentSessionServices) Auth ¶
func (s *AgentSessionServices) Auth() *ai.AuthStorage
Auth returns the credential storage backing auth.json. Read-mostly; safe to share across goroutines (file lock serialises writes). It is nil when the ModelRuntime was created with an injected CredentialStore; use Credentials for the store in effect.
func (*AgentSessionServices) CWD ¶
func (s *AgentSessionServices) CWD() string
CWD returns the working directory this Services container was constructed with.
func (*AgentSessionServices) Close ¶
func (s *AgentSessionServices) Close()
Close stops the Extension Host of the resource loader's default extension load (the loaded extensions stop), stops admission of model background work, cancels its lifetime, and drains admitted tasks. It does not close caller-owned credential or catalog storage. Call it after Sessions finish and outside model callbacks.
func (*AgentSessionServices) Credentials ¶
func (s *AgentSessionServices) Credentials() ai.CredentialStore
Credentials returns the credential store backing model authentication: the auth.json store, or the CredentialStore passed to CreateModelRuntime.
func (*AgentSessionServices) Diagnostics ¶
func (s *AgentSessionServices) Diagnostics() []AgentSessionRuntimeDiagnostic
Diagnostics are the problems found while creating the Services and applying extension flags. Upstream AgentSessionServices.diagnostics.
func (*AgentSessionServices) ExtensionFlagValues ¶
func (s *AgentSessionServices) ExtensionFlagValues() map[string]any
ExtensionFlagValues returns the values the last ApplyExtensionFlagValues accepted, which extensions read with getFlag (agent-session-services.ts sets them on extensionsResult.runtime.flagValues). It is nil before ApplyExtensionFlagValues runs.
func (*AgentSessionServices) ModelRuntime ¶
func (s *AgentSessionServices) ModelRuntime() *ModelRuntime
ModelRuntime returns the one runtime shared by every Session and extension registry facade created from these Services.
func (*AgentSessionServices) Registry ¶
func (s *AgentSessionServices) Registry() *ModelRegistry
Registry returns the model registry. Use Registry().Resolve(provider, model) to obtain a ModelEntry with credentials resolved through configvalue (env vars and !cmd shell prefixes).
func (*AgentSessionServices) ResourceLoader ¶
func (s *AgentSessionServices) ResourceLoader() *DefaultResourceLoader
ResourceLoader returns the loader created from CreateAgentSessionServicesOptions.ResourceLoaderOptions, already reloaded, or nil when none was requested (a Session then builds a default loader). Upstream AgentSessionServices.resourceLoader.
func (*AgentSessionServices) Settings ¶
func (s *AgentSessionServices) Settings() Settings
Settings returns the currently merged settings (global ⊕ project). This is a snapshot; call Settings() again to pick up changes after settings files are edited externally.
func (*AgentSessionServices) SettingsManager ¶
func (s *AgentSessionServices) SettingsManager() *SettingsManager
SettingsManager returns the underlying live settings reader, useful when callers need to call Reload() or inspect global vs project layers separately.
type AgentsFilesResult ¶
type AgentsFilesResult struct {
AgentsFiles []ContextFile
}
AgentsFilesResult is a loader's context files.
type BaseToolOverride ¶
BaseToolOverride is one entry of SessionOptions.BaseToolsOverride: the record key Pi activates and the tool registered for it.
type BashResult ¶
type BashResult struct {
Output string `json:"output"`
// ExitCode is nil when the command has no exit status, including cancellation.
ExitCode *int `json:"exitCode,omitempty"`
Cancelled bool `json:"cancelled"`
Truncated bool `json:"truncated"`
FullOutputPath string `json:"fullOutputPath,omitempty"`
}
BashResult is the result of a direct bash execution via ExecuteBash. Mirrors upstream BashResult (core/bash-executor.ts).
type BranchSummaryEntry ¶
type BranchSummaryEntry = icodingagent.BranchSummaryEntry
BranchSummaryEntry is the persisted branch_summary session entry.
type CacheWarmer ¶
type CacheWarmer interface {
Cancel()
Status() icodingagent.CacheWarmingStatus
OnAgentSettled()
OnModeChanged()
// SetOnWarmed assigns the callback that reports a persisted cache-warming usage entry (Pi's `onWarmed` property).
SetOnWarmed(onWarmed func(context.Context, icodingagent.UsageEntry))
}
CacheWarmer is the part of a cache warmer that a Session drives: Pi's AgentSessionConfig.cacheWarmer, `Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">` (agent-session.ts:266). The caller's stream function starts it; the Session does not.
type CompactionResult ¶
type CompactionResult = icodingagent.CompactionResult
CompactionResult is the result returned by manual compaction. The interactive session handle returns the same type.
type CompactionSettings ¶
type CompactionSettings = compaction.CompactionSettings
CompactionSettings is upstream CompactionSettings (compaction.ts:115), exported with the compaction helpers upstream's index.ts exports.
type CompatibilityRequestConfig ¶
type CompatibilityRequestConfig = icodingagent.CompatibilityRequestConfig
CompatibilityRequestConfig is the request configuration a model falls back to when its provider auth is unconfigured.
type ContextFile ¶
type ContextFile = icodingagent.ContextFile
ContextFile is a loaded project context file (AGENTS.md or CLAUDE.md).
type CreateAgentSessionFromServicesOptions ¶
type CreateAgentSessionFromServicesOptions struct {
Services *AgentSessionServices
// SessionManager is the session log; nil creates a new one for the services' cwd.
SessionManager *SessionManager
// Model is the model to use; nil restores the session's saved model or selects the initial model.
Model *ai.Model
// ThinkingLevel overrides the restored and configured level before clamping to the model.
ThinkingLevel ai.ModelThinkingLevel
ScopedModels []ScopedModel
// Tools is the allowlist of tool names or `*` patterns, or a list of only `+name` and `-name` entries that changes the default selection.
// Nil means no list; a non-nil empty list is an allowlist of nothing.
Tools []string
// ExcludeTools is the denylist of tool names or patterns, applied after Tools.
ExcludeTools []string
// NoTools is "all" (no tools) or "builtin" (no default built-in tools; extension and custom tools stay enabled).
NoTools string
// CustomTools are SDK tool definitions registered in addition to the built-in tools.
CustomTools []extension.ToolDefinition
// SessionStartEvent is the session_start metadata the extension runtime starts with.
SessionStartEvent *extension.SessionStartEvent
}
CreateAgentSessionFromServicesOptions mirrors agent-session-services.ts CreateAgentSessionFromServicesOptions: the services plus the session inputs that must be resolved against their cwd.
type CreateAgentSessionOptions ¶
type CreateAgentSessionOptions struct {
// CWD is the working directory for project-local discovery; empty is the session manager's cwd, else the process's.
CWD string
// AgentDir is the global config directory; empty is the default agent directory.
AgentDir string
// ModelRuntime is the canonical model and auth runtime; nil creates one over AgentDir. A given runtime stays the caller's to close.
ModelRuntime *ModelRuntime
// SettingsManager supplies the settings; nil loads them from AgentDir and CWD.
SettingsManager *SettingsManager
// ResourceLoader supplies the resources the session builds its system prompt from; nil discovers them over CWD.
ResourceLoader ResourceLoader
// SessionManager is the session log; nil creates a new one for CWD.
SessionManager *SessionManager
Model *ai.Model
ThinkingLevel ai.ModelThinkingLevel
ScopedModels []ScopedModel
// Tools, ExcludeTools, NoTools and CustomTools are as in [CreateAgentSessionFromServicesOptions].
Tools []string
ExcludeTools []string
NoTools string
CustomTools []extension.ToolDefinition
SessionStartEvent *extension.SessionStartEvent
}
CreateAgentSessionOptions mirrors sdk.ts:48-106 CreateAgentSessionOptions: everything createAgentSession needs to build its own services and the session. A nil or empty member is an omitted option.
type CreateAgentSessionResult ¶
type CreateAgentSessionResult struct {
Session *Session
// ExtensionsResult is what the services' resource loader loaded (for UI context setup).
ExtensionsResult LoadExtensionsResult
// ModelFallbackMessage warns that the saved model could not be restored, or that no model is available.
ModelFallbackMessage string
}
CreateAgentSessionResult mirrors sdk.ts CreateAgentSessionResult.
func CreateAgentSession ¶
func CreateAgentSession(options CreateAgentSessionOptions) (CreateAgentSessionResult, error)
CreateAgentSession is sdk.ts createAgentSession: it builds the services the options name (cwd, agent directory, settings, model runtime) and a Session over them. Closing the Session releases the services it built; a model runtime or settings manager the caller supplied stays theirs.
func CreateAgentSessionFromServices ¶
func CreateAgentSessionFromServices(options CreateAgentSessionFromServicesOptions) (CreateAgentSessionResult, error)
CreateAgentSessionFromServices creates a Session over previously created services (agent-session-services.ts:214).
type CreateAgentSessionRuntimeFactory ¶
type CreateAgentSessionRuntimeFactory func(context.Context, CreateAgentSessionRuntimeOptions) (CreateAgentSessionRuntimeResult, error)
CreateAgentSessionRuntimeFactory rebuilds destination-CWD Services, resources, tools and extension instances, then constructs a Session over the supplied log. It returns only when construction is complete.
type CreateAgentSessionRuntimeOptions ¶
type CreateAgentSessionRuntimeOptions struct {
CWD string
AgentDir string
SessionManager *SessionManager
SessionStartEvent *extension.SessionStartEvent
// ProjectTrustContext is the trust context of CWD for a replacement that the interactive mode drives (agent-session-runtime.ts:40, 219); its UI serves the project trust prompt. The factory falls back to a headless context without it.
ProjectTrustContext *extension.ProjectTrustContext
}
CreateAgentSessionRuntimeOptions selects the destination log and cwd-bound factory inputs.
type CreateAgentSessionRuntimeResult ¶
type CreateAgentSessionRuntimeResult struct {
Session *Session
Services *AgentSessionServices
// ExtensionsResult is what the Session's resource loader loaded (sdk.ts CreateAgentSessionResult.extensionsResult).
ExtensionsResult LoadExtensionsResult
// Diagnostics are the startup diagnostics of the construction. Runtime.Diagnostics returns them until a replacement applies its own.
Diagnostics []AgentSessionRuntimeDiagnostic
// ModelFallbackMessage reports a saved model that could not be restored, or that no model is available. Runtime.ModelFallbackMessage returns it until a replacement applies its own.
ModelFallbackMessage string
// Dispose requests retirement of factory-owned resources after logical Session disposal. It must not wait for callbacks that replacement has not invoked yet.
Dispose func(reason string)
}
CreateAgentSessionRuntimeResult is agent-session-runtime.ts:23 `interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult`: the members of CreateAgentSessionResult (Session, ExtensionsResult, ModelFallbackMessage) and the Services and Diagnostics of the construction, flat as in 0.4.1. A factory carries the created result's members over as Pi's does ({ ...created, services, diagnostics }, main.ts:839-860).
type CreateAgentSessionServicesOptions ¶
type CreateAgentSessionServicesOptions struct {
// CWD is the project directory used to discover per-project
// settings (.pig/settings.json) and to anchor session storage.
// Empty uses SessionManager.GetCwd when supplied, otherwise os.Getwd().
CWD string
// SessionManager supplies the CWD default when CWD is empty. It remains caller-owned; SessionOptions selects the log used by a Session.
SessionManager *SessionManager
// AgentDir is the global pig config directory (typically
// ~/.pig/agent). Empty → DefaultAgentDir().
AgentDir string
// ProjectTrusted controls whether project-local settings are loaded. nil
// preserves the SDK default of trusted project settings.
ProjectTrusted *bool
// SettingsManager supplies caller-owned file or memory settings instead of loading settings files.
SettingsManager *SettingsManager
// ModelRuntime shares a caller-owned runtime instead of creating one over AgentDir; the Services then use its
// registry and credentials and never close it. Upstream CreateAgentSessionServicesOptions.modelRuntime.
ModelRuntime *ModelRuntime
// ModelRuntimeSignal bounds the model catalog restore and the first availability refresh of the runtime the Services
// create; nil never cancels. Upstream CreateAgentSessionServicesOptions.modelRuntimeSignal (an AbortSignal).
ModelRuntimeSignal context.Context
// ExtensionFlagValues are the CLI values for extension flags in command-line order (a JavaScript Map keeps insertion order,
// and the order shows in diagnostics): true for a boolean flag, a string for a string flag.
// [Services.ApplyExtensionFlagValues] validates them against the loaded extensions.
// Upstream CreateAgentSessionServicesOptions.extensionFlagValues (Map<string, boolean | string>).
ExtensionFlagValues []ExtensionFlagValue
// ResourceLoaderOptions configure the Services' resource loader; its CWD, AgentDir and SettingsManager are the
// Services' own. Upstream CreateAgentSessionServicesOptions.resourceLoaderOptions
// (Omit<DefaultResourceLoaderOptions, "cwd" | "agentDir" | "settingsManager">). Nil leaves the resource loader to
// the Session, which builds a default one.
ResourceLoaderOptions *DefaultResourceLoaderOptions
// ResourceLoader is a caller-owned, already reloaded resource loader the Services use as their own instead of building one; Close does not close it. Upstream createAgentSession's `resourceLoader` option. It takes precedence over ResourceLoaderOptions.
ResourceLoader *DefaultResourceLoader
// ResourceLoaderReloadOptions are the options of the Services' first resource reload. Upstream
// CreateAgentSessionServicesOptions.resourceLoaderReloadOptions. Nil or empty reloads without resolving trust.
ResourceLoaderReloadOptions *ResourceLoaderReloadOptions
}
CreateAgentSessionServicesOptions configures CreateAgentSessionServices. All fields are optional; empty values resolve to sensible defaults (current working directory, $PIG_HOME/agent or ~/.pig/agent).
type CreateModelRuntimeOptions ¶
type CreateModelRuntimeOptions struct {
// Credentials replaces the auth.json store at AuthPath. When set, no auth.json is opened.
Credentials ai.CredentialStore
AuthPath string
ModelsPath **string
ModelsStore ai.ModelsStore
ModelsStorePath string
AllowModelNetwork bool
ModelRefreshTimeoutMs *int
// CatalogBaseURL is the base URL of the remote model catalog; empty selects the default.
// upstream: model-runtime.ts:CreateModelRuntimeOptions.catalogBaseUrl
CatalogBaseURL string
RefreshOnCreate *bool
}
CreateModelRuntimeOptions selects file paths, catalog storage, and initial refresh behavior. Signal is the context passed to CreateModelRuntime. ModelsPath uses two pointers to preserve omitted, null, and string: nil selects the default; a pointer to nil disables models.json.
type CredentialSynchronizationError ¶
type CredentialSynchronizationError = icodingagent.CredentialSynchronizationError
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 })`.
type CredentialSynchronizationOperation ¶
type CredentialSynchronizationOperation = icodingagent.CredentialSynchronizationOperation
type CutPointResult ¶
type CutPointResult = compaction.CutPointResult
CutPointResult is upstream CutPointResult (compaction.ts:383).
func FindCutPoint ¶
func FindCutPoint(entries []SessionEntry, startIndex, endIndex, keepRecentTokens int) CutPointResult
FindCutPoint is upstream findCutPoint: the entry index to keep from so that about keepRecentTokens of recent context remains between startIndex and endIndex (exclusive).
type DefaultResourceLoader ¶
type DefaultResourceLoader struct {
// contains filtered or unexported fields
}
DefaultResourceLoader resolves skills, prompt templates, context files and system prompt files from the default user and project resource locations, the settings-configured paths, the configured Packages and the additional paths, applying project trust as Pi's does, and installs a missing npm or git Package as Pi's package manager does. It loads themes, and extensions through the LoadExtensions hook the Extension Host supplies. A new loader is empty until Reload runs, as Pi's DefaultResourceLoader is.
func NewDefaultResourceLoader ¶
func NewDefaultResourceLoader(opts DefaultResourceLoaderOptions) *DefaultResourceLoader
NewDefaultResourceLoader returns an empty loader over the options' cwd and agent directory, each resolved with resolvePath as the resource-loader.ts DefaultResourceLoader constructor does ("~" expansion, file URL, absolute path). Call Reload to discover resources.
func (*DefaultResourceLoader) Close ¶
func (l *DefaultResourceLoader) Close()
Close shuts down the Extension Host the default extension load started. The loaded extensions stop.
func (*DefaultResourceLoader) ExtendResources ¶
func (l *DefaultResourceLoader) ExtendResources(paths ResourceExtensionPaths) error
ExtendResources adds the skills, prompt templates and themes extensions contributed to the ones the last Reload found (resource-loader.ts extendResources). Each path records its metadata as the source info of the resources under it; the loader then reloads the collection from the previous paths plus the new ones. A path that cannot be resolved fails the call, and collections updated before it stay updated.
func (*DefaultResourceLoader) GetAgentsFiles ¶
func (l *DefaultResourceLoader) GetAgentsFiles() AgentsFilesResult
GetAgentsFiles returns the context files found by the last Reload.
func (*DefaultResourceLoader) GetAppendSystemPrompt ¶
func (l *DefaultResourceLoader) GetAppendSystemPrompt() []string
GetAppendSystemPrompt returns the APPEND_SYSTEM.md text found by the last Reload.
func (*DefaultResourceLoader) GetAppendSystemPromptSources ¶
func (l *DefaultResourceLoader) GetAppendSystemPromptSources() []ResourceSource
GetAppendSystemPromptSources returns the files the appended texts were read from by the last Reload.
func (*DefaultResourceLoader) GetExtensions ¶
func (l *DefaultResourceLoader) GetExtensions() LoadExtensionsResult
GetExtensions returns the extensions found by the last Reload (resource-loader.ts getExtensions).
func (*DefaultResourceLoader) GetPrompts ¶
func (l *DefaultResourceLoader) GetPrompts() PromptsResult
GetPrompts returns the prompt templates found by the last Reload.
func (*DefaultResourceLoader) GetSkills ¶
func (l *DefaultResourceLoader) GetSkills() SkillsResult
GetSkills returns the skills found by the last Reload.
func (*DefaultResourceLoader) GetSystemPrompt ¶
func (l *DefaultResourceLoader) GetSystemPrompt() (string, bool)
GetSystemPrompt returns the SYSTEM.md text found by the last Reload.
func (*DefaultResourceLoader) GetSystemPromptSource ¶
func (l *DefaultResourceLoader) GetSystemPromptSource() (ResourceSource, bool)
GetSystemPromptSource returns the file the system prompt was read from by the last Reload; false when it came from literal text or there is none.
func (*DefaultResourceLoader) GetThemes ¶
func (l *DefaultResourceLoader) GetThemes() ThemesResult
GetThemes returns the themes found by the last Reload and ExtendResources (resource-loader.ts getThemes).
func (*DefaultResourceLoader) LoadProjectTrustExtensions ¶
func (l *DefaultResourceLoader) LoadProjectTrustExtensions(ctx context.Context) (LoadExtensionsResult, error)
LoadProjectTrustExtensions loads the extension set with project settings forced untrusted and returns it (resource-loader.ts loadProjectTrustExtensions). The loader's settings stay untrusted until the next Reload or an explicit trust decision.
func (*DefaultResourceLoader) Reload ¶
func (l *DefaultResourceLoader) Reload(options ...ResourceLoaderReloadOptions) error
Reload reloads the settings, then rediscovers every resource for their current project trust (resource-loader.ts reload). Reloading the settings discards transient overrides applied with ApplyOverrides. A failure while resolving the Packages, settings entries or skills leaves the previous results in place; a failure while resolving the prompt templates keeps the new skills and the previous other results, as Pi's reload does. The optional options decide project trust first, as DefaultResourceLoader.ReloadWith does with a context of context.Background().
func (*DefaultResourceLoader) ReloadWith ¶
func (l *DefaultResourceLoader) ReloadWith(ctx context.Context, options ...ResourceLoaderReloadOptions) error
ReloadWith is Reload with the context ctx. A ResolveProjectTrust in options first loads the bootstrap extension set with project settings forced untrusted and hands it to the callback, then applies the answer to the settings (resource-loader.ts reload(options)); the final extension set reuses the bootstrap load. A failed decision or bootstrap load fails the reload and leaves the previous results in place, with the project untrusted as the bootstrap pass left it.
type DefaultResourceLoaderOptions ¶
type DefaultResourceLoaderOptions struct {
CWD string
AgentDir string
// SettingsManager supplies the project trust, the settings-configured resource paths and the Packages. Nil reads the settings files under CWD and AgentDir with trusted project settings.
SettingsManager *SettingsManager
// AdditionalSkillPaths are skill files or directories loaded after the resolved skills; they are the loader's explicit paths (resource-loader.ts additionalSkillPaths).
AdditionalSkillPaths []string
// AdditionalPromptTemplatePaths are prompt template files or directories loaded after the resolved prompt templates.
AdditionalPromptTemplatePaths []string
// AdditionalThemePaths are theme files or directories loaded after the resolved themes.
AdditionalThemePaths []string
// NoThemes keeps only AdditionalThemePaths.
NoThemes bool
// NoSkills keeps only AdditionalSkillPaths.
NoSkills bool
// NoPromptTemplates keeps only AdditionalPromptTemplatePaths.
NoPromptTemplates bool
// NoContextFiles loads no AGENTS.md or CLAUDE.md context files.
NoContextFiles bool
// SystemPrompt is the system prompt text, or the path of a file holding it, that replaces discovery of SYSTEM.md. Nil discovers SYSTEM.md.
SystemPrompt *string
// AppendSystemPrompt is the appended texts, or paths of files holding them, that replace discovery of APPEND_SYSTEM.md. Nil discovers it; an empty non-nil list appends nothing.
AppendSystemPrompt []string
// SkillsOverride, PromptsOverride, AgentsFilesOverride, SystemPromptOverride and AppendSystemPromptOverride transform what the loader found (resource-loader.ts *Override).
SkillsOverride func(SkillsResult) SkillsResult
PromptsOverride func(PromptsResult) PromptsResult
ThemesOverride func(ThemesResult) ThemesResult
ExtensionsOverride func(LoadExtensionsResult) LoadExtensionsResult
AgentsFilesOverride func(AgentsFilesResult) AgentsFilesResult
SystemPromptOverride func(*string) *string
AppendSystemPromptOverride func([]string) []string
// AdditionalExtensionPaths are extension sources (-e arguments) resolved as temporary extensions; they load before the settings and Package extensions (resource-loader.ts additionalExtensionPaths).
AdditionalExtensionPaths []string
// NoExtensions keeps only AdditionalExtensionPaths.
NoExtensions bool
// ExtensionFactories are the inline and built-in extensions (resource-loader.ts extensionFactories): a bare factory or named input loads as
// `<inline:name>`; an input with Builtin supplies the code of its `builtin:<name>` path. They register against the loader's runtime.
ExtensionFactories []extension.InlineExtension
// EventBus is the extension-to-extension bus the factories share; nil creates one.
EventBus extension.EventBus
// DisabledBuiltinExtensions names the built-in extensions whose `builtin:<name>` paths are left out of the extension set (resource-loader.ts disabledBuiltinExtensions).
DisabledBuiltinExtensions []string
// LoadExtensions loads the extension set of a reload; nil loads the extension files of the resolved Packages and settings and of AdditionalExtensionPaths through a subprocess Extension Host (resource-loader.ts:513-600). A reload with ResolveProjectTrust calls it first for the bootstrap pass, then once for the final set.
LoadExtensions func(ctx context.Context, request ExtensionLoadRequest) (LoadExtensionsResult, error)
}
DefaultResourceLoaderOptions configures NewDefaultResourceLoader (resource-loader.ts DefaultResourceLoaderOptions). LoadExtensions replaces the loader's own extension loading; extensionFactories, built-in extensions and the event bus are not options of this loader, because the Extension Host runs file extensions out of process.
type ExecuteBashOptions ¶
type ExecuteBashOptions struct {
// ExcludeFromContext is the optional excludeFromContext of upstream executeBash: nil leaves the member out of the recorded message.
ExcludeFromContext *bool
ID *string
Operations extension.BashOperations
}
ExecuteBashOptions is the options object of upstream executeBash. ExcludeFromContext persists the result as a `bashExecution` entry but drops it from LLM context (the `!!cmd` semantics, via bashExecutionToText); ID is the optional correlation identifier of the output events; a nil Operations runs the local shell.
type ExportToHTMLOptions ¶
type ExportToHTMLOptions struct {
// ThemeName exports with this theme when it is registered; otherwise the settings theme, then the active theme.
ThemeName string
}
ExportToHTMLOptions is exportToHtml's presentation settings (agent-session.ts exportToHtml options).
type ExtensionBindings ¶
type ExtensionBindings struct {
UIContext extension.UIContext
CommandContextActions extension.CommandActions
Mode extension.ExtensionMode
// AbortHandler replaces the default abort of the extension context (agent-session.ts:3443-3447).
AbortHandler func()
// ShutdownHandler backs ctx.shutdown() (agent-session.ts:3451).
ShutdownHandler func()
// OnError receives extension errors; a later binding replaces the earlier listener (agent-session.ts:3340-3343).
OnError extension.ErrorListener
}
ExtensionBindings supplies mode-owned UI, command actions and handlers before session_start dispatch (upstream ExtensionBindings, agent-session.ts:300-307). A field left at its zero value is Pi's undefined: BindExtensions keeps the earlier value for it.
type ExtensionFlagValue ¶
ExtensionFlagValue is one entry of CreateAgentSessionServicesOptions.ExtensionFlagValues: the value of --Name, a bool or a string.
type ExtensionHost ¶
type ExtensionHost interface {
// UIBridge returns the bridge that carries the subprocess extensions' UI requests and host actions, or nil when no subprocess extension host runs.
UIBridge() *subprocess.UIBridge
// FlushCommands applies the stdin-end window to the commands of runtimes that report none.
FlushCommands()
// SetRuntimeDrainHandler installs the handler that runs when the extension runtimes report that nothing keeps their event loops alive.
SetRuntimeDrainHandler(fn func())
// SetSettleTailHandler installs the handler that receives the count of extension calls that keep a settle tail open.
SetSettleTailHandler(fn func(suspended int))
// SetBackgroundCallGate installs the hold on the UI calls that no request started: a call waits while the gate returns a channel and runs when it closes.
SetBackgroundCallGate(gate func() <-chan struct{})
// SetCommandSuspendHandler installs the handler that receives the count of in-flight extension commands that are suspended.
SetCommandSuspendHandler(fn func(suspended int))
// SetCommandWindowHandler installs the handler that receives the count of in-flight extension commands still inside their own window.
SetCommandWindowHandler(fn func(suspended int))
// SetTimerTurns gives the host the mode's model of Pi's event loop, so a host call an extension runtime marks as made by a timer or an immediate waits for the loop's turn.
SetTimerTurns(turns *jsloop.Turns)
// Invalidate makes this Session's extension host reject every later call of its extension processes with message, the stale message of the runner that fronted them.
Invalidate(message string)
// EndInput tells every host of the process, and each host created later, that no further input can arrive.
EndInput()
// HoldRetirements keeps every host a later retirement would release running until TerminateProcesses.
HoldRetirements()
// TerminateProcesses kills the extension processes of every live host. Only a process about to exit calls it.
TerminateProcesses()
}
ExtensionHost is the extension host behind the runner of the Sessions a Runtime creates. Pi runs extensions in its own process, so a mode reaches them through AgentSession alone; Pig runs file extensions in subprocesses (D19), and a mode reaches the controls of those processes through the Session that owns them, with Session.ExtensionHost.
The process controls (EndInput, HoldRetirements and TerminateProcesses) act on every host of the process that created the Session, including the hosts of replaced Sessions that still finish a command and of Sessions created later (D70). Pi has one Node process, so those controls have no Pi counterpart.
type ExtensionLoadError ¶
type ExtensionLoadError struct{ Path, Error string }
ExtensionLoadError is one {path, error} entry of types.ts LoadExtensionsResult.errors.
type ExtensionLoadRequest ¶
type ExtensionLoadRequest struct {
// Bootstrap marks the pass that runs with project settings forced untrusted: it loads the user and temporary extensions and keeps project-local ones out (resource-loader.ts loadProjectTrustExtensions).
Bootstrap bool
// PreTrust is the bootstrap result a final pass reuses; nil when no bootstrap pass ran.
PreTrust *LoadExtensionsResult
}
ExtensionLoadRequest asks DefaultResourceLoaderOptions.LoadExtensions for one pass of the extension set.
type ExtensionLoadWarning ¶
type ExtensionLoadWarning struct{ Path, Warning string }
ExtensionLoadWarning is one {path, warning} entry of types.ts LoadExtensionsResult.warnings.
type ExtensionOAuthConfig ¶
type ExtensionOAuthConfig = icodingagent.ExtensionOAuthConfig
type ExtensionResourcePath ¶
type ExtensionResourcePath struct {
Path string
Metadata icodingagent.PathMetadata
}
ExtensionResourcePath is one {path, metadata} entry of types.ts ResourceExtensionPaths.
type ExtensionRunStage ¶
type ExtensionRunStage struct {
Prepare func(ctx context.Context, prepare func(context.Context))
Start func(start func())
}
ExtensionRunStage places the two steps of a run that an extension starts with sendUserMessage, or with an idle triggerTurn sendMessage, for a mode that orders them against output of its own. Prepare runs prepare, the input handlers, compaction check and before_agent_start, with ctx or a context derived from it; the preparation then passes Start the step that emits agent_start. Either may run its step later or on another goroutine, but each runs its step exactly once.
type ForkMessage ¶
ForkMessage pairs a session entry ID with the user message text. Returned by UserMessagesForForking, used by the `get_fork_messages` RPC command. Mirrors upstream getUserMessagesForForking return type (agent-session.ts:2856-2875).
type GraphModelRuntime ¶
type GraphModelRuntime struct {
// contains filtered or unexported fields
}
GraphModelRuntime is a ModelRuntime an extension constructed.
func (*GraphModelRuntime) Call ¶
func (g *GraphModelRuntime) Call(ctx context.Context, method string, raw json.RawMessage) (any, error)
Call runs a ModelRuntime method.
func (*GraphModelRuntime) Release ¶
func (g *GraphModelRuntime) Release()
Release implements subprocess.SessionGraphReleaser.
func (*GraphModelRuntime) Runtime ¶
func (g *GraphModelRuntime) Runtime() *ModelRuntime
Runtime is the model runtime the handle names. A session created from it shares it, as Pi's createAgentSession shares the modelRuntime it is given.
func (*GraphModelRuntime) StreamModel ¶
func (g *GraphModelRuntime) StreamModel(ctx context.Context, model map[string]any, request map[string]any) (*ai.AssistantMessageEventStream, error)
StreamModel implements subprocess.SessionGraphStreamer: Pi's ModelRuntime.stream and streamSimple of the model object and request the extension sent.
type GraphPackageManager ¶
type GraphPackageManager struct {
// contains filtered or unexported fields
}
GraphPackageManager is a DefaultPackageManager an extension constructed.
func (*GraphPackageManager) Call ¶
func (g *GraphPackageManager) Call(ctx context.Context, method string, raw json.RawMessage) (any, error)
Call runs a DefaultPackageManager method.
type GraphResourceLoader ¶
type GraphResourceLoader struct {
// contains filtered or unexported fields
}
GraphResourceLoader is a DefaultResourceLoader an extension constructed.
func (*GraphResourceLoader) Call ¶
func (g *GraphResourceLoader) Call(ctx context.Context, method string, raw json.RawMessage) (any, error)
Call runs a DefaultResourceLoader method.
func (*GraphResourceLoader) Loader ¶
func (g *GraphResourceLoader) Loader() *DefaultResourceLoader
Loader is the loader the handle names. A session created from it shares it, as Pi's createAgentSession shares the ResourceLoader it is given.
func (*GraphResourceLoader) Release ¶
func (g *GraphResourceLoader) Release()
Release implements subprocess.SessionGraphReleaser: when the last holder lets go (the extension's handle and every session created over the loader), the Extension Host the loader started for its extensions shuts down. Pi's extensions live in the importing process and need no close; here they are processes.
type LoadExtensionsResult ¶
type LoadExtensionsResult struct {
Extensions []extension.Extension
Errors []ExtensionLoadError
Warnings []ExtensionLoadWarning
// Runtime is the runtime the extensions of this load share; the runner the Session builds over them binds it (agent-session.ts _buildRuntime passes extensionsResult.runtime to the ExtensionRunner). nil means the runner owns a fresh one.
Runtime *extension.ExtensionRuntime
// contains filtered or unexported fields
}
LoadExtensionsResult is types.ts LoadExtensionsResult: the extensions of a load with its errors and warnings, and the runtime they share.
func DiscoverAndLoadExtensions ¶
func DiscoverAndLoadExtensions(ctx context.Context, configuredPaths []string, cwd, agentDir string) (LoadExtensionsResult, error)
DiscoverAndLoadExtensions discovers extensions in the standard locations and loads them: the project's `<cwd>/<config dir>/extensions` (`.pi` in Pi), the global `<agentDir>/extensions`, then each configured path, deduplicated by absolute path in that order. An empty agentDir is the agent directory of the process. Load failures are in the result's Errors, as in Pi.
Ports packages/coding-agent/src/core/extensions/loader.ts discoverAndLoadExtensions (:828-875), discoverExtensionsInDir and resolveExtensionEntries. Pi imports each file into its own process; PiG loads it in the Extension Host (D19).
pig divergence (D117): Pi's optional event bus parameter does not exist; the Extension Host owns the routing of pi.events and a caller cannot supply a bus.
func (LoadExtensionsResult) Close ¶
func (r LoadExtensionsResult) Close()
Close shuts down the Extension Host that DiscoverAndLoadExtensions started for the result's extensions. Pi's extensions live in the importing process and need no close. A result from another source has no host and Close does nothing.
func (LoadExtensionsResult) UIBridge ¶
func (r LoadExtensionsResult) UIBridge() *subprocess.UIBridge
UIBridge is the UI bridge of the Extension Host that loaded the result's extensions, which carries the Session state the extensions' contexts read; nil for a result from another source. It has no UI: contexts that read it report hasUI false and its dialogs answer nothing, as Pi's headless extension context does.
type ModelCycleResult ¶
type ModelCycleResult = icodingagent.ModelCycleResult
ModelCycleResult reports a model-cycle selection and its clamped thinking level.
type ModelMutationOptions ¶
type ModelMutationOptions = icodingagent.ModelMutationOptions
ModelMutationOptions controls whether a Session mutation also saves a global default.
type ModelRegistry ¶
type ModelRegistry struct {
*icodingagent.ModelRegistry
// contains filtered or unexported fields
}
ModelRegistry is the extension-facing synchronous facade over model lookup and the one Services-owned ModelRuntime.
func NewModelRegistry ¶
func NewModelRegistry(runtime *ModelRuntime) *ModelRegistry
NewModelRegistry is the synchronous facade over runtime's registry (model-registry.ts constructor(runtime)). Services builds the one facade of its runtime this way.
func (*ModelRegistry) Classify ¶
func (registry *ModelRegistry) Classify(ctx context.Context, model *ai.ClassifierModel, request ai.ClassifierContext, options ...ai.ModelsClassifierOptions) ai.ClassifierResult
Classify classifies structured state with request-time authentication. It never fails: failures are error or aborted results (model-registry.ts classify).
func (*ModelRegistry) Complete ¶
func (registry *ModelRegistry) Complete(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessage
Complete delegates to ModelRuntime.Complete and returns its terminal pointer.
func (*ModelRegistry) Find ¶
func (registry *ModelRegistry) Find(provider, id string) *ai.Model
Find returns an exact runtime model, including native provider registrations.
func (*ModelRegistry) FindOfType ¶
func (registry *ModelRegistry) FindOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
FindOfType finds a model of a non-chat type, for example FindOfType(ai.ModelTypeClassifier, "typesafe", "jev-latest") (model-registry.ts findOfType).
func (*ModelRegistry) GenerateImages ¶
func (registry *ModelRegistry) GenerateImages(ctx context.Context, model *ai.ImageModel, request ai.ImagesContext, options ...ai.ModelsImagesOptions) ai.AssistantImages
GenerateImages generates images with request-time authentication. It never fails: failures are error or aborted results (model-registry.ts generateImages).
func (*ModelRegistry) GetAPIKeyAndHeaders ¶
func (registry *ModelRegistry) GetAPIKeyAndHeaders(ctx context.Context, model *ai.Model) ResolvedRequestAuth
GetAPIKeyAndHeaders returns compatibility headers even for an unconfigured provider.
func (*ModelRegistry) GetAPIKeyForProvider ¶
func (registry *ModelRegistry) GetAPIKeyForProvider(ctx context.Context, id string) *string
GetAPIKeyForProvider returns nil when authentication is absent or fails, as the compatibility facade specifies.
func (*ModelRegistry) GetAll ¶
func (registry *ModelRegistry) GetAll() []*ai.Model
GetAll returns the full model catalog without resolving request credentials (model-registry.ts getAll). Each model carries its cost through Capabilities (ai.Model.CostRates).
func (*ModelRegistry) GetAvailable ¶
func (registry *ModelRegistry) GetAvailable() []*ai.Model
GetAvailable returns the models of providers with configured auth from the last published availability, without credential or catalog I/O (model-registry.ts getAvailable).
func (*ModelRegistry) GetAvailableOfType ¶
func (registry *ModelRegistry) GetAvailableOfType(ctx context.Context, modelType ai.ModelType, provider ...string) ([]ai.AnyModel, error)
GetAvailableOfType lists the models of a type whose provider has working credentials (model-registry.ts getAvailableOfType).
func (*ModelRegistry) GetError ¶
func (registry *ModelRegistry) GetError() string
GetError returns the current model configuration diagnostic, or an empty string.
func (*ModelRegistry) GetModelOfType ¶
func (registry *ModelRegistry) GetModelOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
GetModelOfType looks up a model of a type by provider and ID (model-registry.ts getModelOfType).
func (*ModelRegistry) GetModelsOfType ¶
func (registry *ModelRegistry) GetModelsOfType(modelType ai.ModelType, provider ...string) []ai.AnyModel
GetModelsOfType lists every known model of a type, optionally for one provider (model-registry.ts getModelsOfType).
func (*ModelRegistry) GetProviderAuth ¶
func (registry *ModelRegistry) GetProviderAuth(ctx context.Context, id string) (*ai.AuthResult, error)
GetProviderAuth resolves current provider authentication without caching configuration commands.
func (*ModelRegistry) GetProviderAuthStatus ¶
func (registry *ModelRegistry) GetProviderAuthStatus(id string) ai.AuthStatus
GetProviderAuthStatus reports where a provider's credentials come from. Like model-registry.ts:120 it asks the model runtime, whose status covers a provider of only virtual models (model-runtime.ts getProviderAuthStatus over the snapshot registerVirtualModel updates).
func (*ModelRegistry) HasConfiguredAuth ¶
func (registry *ModelRegistry) HasConfiguredAuth(model *ai.Model) bool
HasConfiguredAuth reports whether the model's provider has configured auth (model-registry.ts hasConfiguredAuth(model)).
func (*ModelRegistry) IsUsingOAuth ¶
func (registry *ModelRegistry) IsUsingOAuth(model *ai.Model) bool
IsUsingOAuth reports whether the model's provider is authenticated with OAuth in the latest published availability snapshot (model-registry.ts isUsingOAuth).
func (*ModelRegistry) Refresh ¶
func (registry *ModelRegistry) Refresh(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
Refresh reloads models.json and the provider catalogs and returns the outcome (model-registry.ts:56 refresh, which hands it to runtime.refresh). It hides the embedded registry's Refresh(), which reloads synchronously without options.
func (*ModelRegistry) RegisterProvider ¶
func (registry *ModelRegistry) RegisterProvider(name string, config ProviderConfigInput) error
RegisterProvider registers a provider by name with its core configuration (model-registry.ts registerProvider(providerName, config)). ModelRuntime.RegisterNativeProvider is its Provider overload, and RegisterExtensionProvider (promoted from the internal registry) takes the extension host's distinct Go registration payload.
func (*ModelRegistry) RegisterProviderObject ¶
func (registry *ModelRegistry) RegisterProviderObject(provider *ai.ModelsProvider) error
RegisterProviderObject registers a Provider object (model-registry.ts:210 registerProvider(provider: Provider), which hands it to runtime.registerNativeProvider at :218). Go names the overload apart from RegisterProvider(name, config); the promoted RegisterNativeProvider takes the extension host's payload.
func (*ModelRegistry) RegisterVirtualModel ¶
func (registry *ModelRegistry) RegisterVirtualModel(definition VirtualModelDefinition) error
RegisterVirtualModel registers a virtual model with the runtime. It is the registry action extensions' `registerVirtualModel` reaches.
upstream: runner.ts:497-500 (registry.registerVirtualModel)
func (*ModelRegistry) Stream ¶
func (registry *ModelRegistry) Stream(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
Stream delegates to the Services-owned ModelRuntime.
func (*ModelRegistry) StreamSimple ¶
func (registry *ModelRegistry) StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
StreamSimple delegates to the same runtime preparation and streaming path.
func (*ModelRegistry) UnregisterVirtualModel ¶
func (registry *ModelRegistry) UnregisterVirtualModel(provider, id string)
UnregisterVirtualModel removes a virtual model from the runtime.
upstream: runner.ts:538-541 (registry.unregisterVirtualModel)
type ModelRoute ¶
type ModelRoute = extension.ModelRoute
ModelRoute is the physical model and thinking level for one request. upstream: virtual-models.ts:75-85
type ModelRouteReason ¶
type ModelRouteReason = extension.ModelRouteReason
ModelRouteReason says why a request is being routed. upstream: virtual-models.ts:53
type ModelRouteRequest ¶
type ModelRouteRequest = extension.ModelRouteRequest
ModelRouteRequest is what a router sees for one request. upstream: virtual-models.ts:55-72
type ModelRuntime ¶
type ModelRuntime struct {
// contains filtered or unexported fields
}
ModelRuntime is the mode-independent model execution path owned by Services and shared by every Session and extension ModelRegistry facade.
func CreateModelRuntime ¶
func CreateModelRuntime(ctx context.Context, options CreateModelRuntimeOptions) (*ModelRuntime, error)
CreateModelRuntime creates a model runtime without a Session. The caller owns ModelRuntime.Close. Initial refresh restores cached catalogs without network unless explicitly enabled, and shares the caller's cancellation with every refresh operation.
func NewModelRuntime ¶
func NewModelRuntime(services *AgentSessionServices) (*ModelRuntime, error)
NewModelRuntime constructs a runtime backed by services model configuration and credentials.
func (*ModelRuntime) CancelDeferred ¶
func (runtime *ModelRuntime) CancelDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, options ...ai.DeferredCancelOptions) error
func (*ModelRuntime) CheckAuth ¶
func (runtime *ModelRuntime) CheckAuth(ctx context.Context, providerID string) (*ai.AuthCheck, error)
CheckAuth checks the provider's current authentication contract.
func (*ModelRuntime) Classify ¶
func (runtime *ModelRuntime) Classify(ctx context.Context, model *ai.ClassifierModel, request ai.ClassifierContext, options ...ai.ModelsClassifierOptions) ai.ClassifierResult
Classify classifies structured state through the owning provider with auth resolved like a chat request. It never returns an error: a model that is not a classifier, an unknown provider, unconfigured auth, cancellation and a provider without classification become an error or aborted result.
func (*ModelRuntime) Close ¶
func (runtime *ModelRuntime) Close()
Close cancels and drains the Services-owned model task group. It also gives callers of CreateModelRuntime an explicit lifetime endpoint; Session Runtime.Close does not close caller-supplied Services.
func (*ModelRuntime) Complete ¶
func (runtime *ModelRuntime) Complete(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessage
Complete returns the exact terminal pointer produced by Stream.Result.
func (*ModelRuntime) CompleteSimple ¶
func (runtime *ModelRuntime) CompleteSimple(ctx context.Context, model *ai.Model, request ai.Context, options ...ai.StreamOptions) *ai.AssistantMessage
CompleteSimple returns the exact terminal pointer produced by StreamSimple.
func (*ModelRuntime) FetchDeferred ¶
func (runtime *ModelRuntime) FetchDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, options ...ai.DeferredFetchOptions) *ai.AssistantMessage
func (*ModelRuntime) GenerateImages ¶
func (runtime *ModelRuntime) GenerateImages(ctx context.Context, model *ai.ImageModel, request ai.ImagesContext, options ...ai.ModelsImagesOptions) ai.AssistantImages
GenerateImages generates images through the owning provider with auth resolved like a chat request. It never returns an error: an unknown provider, unconfigured auth, cancellation and a provider without image generation become an error or aborted result.
func (*ModelRuntime) GetAllAvailable ¶
func (runtime *ModelRuntime) GetAllAvailable(ctx context.Context, providerID ...string) ([]ai.AnyModel, error)
GetAllAvailable lists the models of every type whose provider has working credentials, for one provider or all. Chat models are the same bound models GetAvailable returns.
func (*ModelRuntime) GetAllModels ¶
func (runtime *ModelRuntime) GetAllModels(providerID ...string) []ai.AnyModel
GetAllModels lists the last-known models of every type from one provider or all providers. Chat models are the same bound models GetModel returns.
func (*ModelRuntime) GetAuth ¶
func (runtime *ModelRuntime) GetAuth(ctx context.Context, providerID string, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
GetAuth resolves the auth of one provider. GetModelAuth is Pi's getAuth(model) overload.
func (*ModelRuntime) GetAvailable ¶
func (runtime *ModelRuntime) GetAvailable(ctx context.Context, providerID ...string) ([]*ai.Model, error)
GetAvailable fails fast on the first availability rejection while Services owns the remaining work. Success waits for fresh availability and publishes a full pass only if no newer full/provider synchronization superseded it. A provider-only query returns its own result without replacing the shared snapshot.
func (*ModelRuntime) GetAvailableOfType ¶
func (runtime *ModelRuntime) GetAvailableOfType(ctx context.Context, modelType ai.ModelType, providerID ...string) ([]ai.AnyModel, error)
GetAvailableOfType lists the models of one type whose provider has working credentials. Chat models follow the provider's chat availability, so the chat list matches GetAvailable; every other model type is kept (models.ts getAvailableOfType, getAllAvailable).
func (*ModelRuntime) GetAvailableSnapshot ¶
func (runtime *ModelRuntime) GetAvailableSnapshot() []*ai.Model
GetAvailableSnapshot returns the last published availability without credential or catalog I/O. Provider registration and removal update it before returning.
func (*ModelRuntime) GetCompatibilityRequestConfig ¶
func (runtime *ModelRuntime) GetCompatibilityRequestConfig(model *ai.Model) (CompatibilityRequestConfig, error)
GetCompatibilityRequestConfig resolves the configured headers and authHeader flag of a model. A header that cannot be resolved is an error.
func (*ModelRuntime) GetError ¶
func (runtime *ModelRuntime) GetError() string
GetError joins model configuration errors and the latest non-cancelled availability failure.
func (*ModelRuntime) GetModel ¶
func (runtime *ModelRuntime) GetModel(providerID, modelID string) *ai.Model
GetModel returns a registered model by exact provider and model ID without synthesizing unknown identities.
func (*ModelRuntime) GetModelAuth ¶
func (runtime *ModelRuntime) GetModelAuth(ctx context.Context, model ai.AnyModel, overrides ...ai.AuthResolutionOverrides) (*ai.AuthResult, error)
GetModelAuth resolves request auth for a model of any type. Auth is provider-scoped, so one credential serves chat, image and classifier models.
func (*ModelRuntime) GetModelOfType ¶
func (runtime *ModelRuntime) GetModelOfType(modelType ai.ModelType, providerID, modelID string) ai.AnyModel
GetModelOfType looks up one model of the given type, or returns nil.
func (*ModelRuntime) GetModels ¶
func (runtime *ModelRuntime) GetModels(providerID ...string) []*ai.Model
GetModels returns metadata snapshots for the complete static and explicitly registered model catalog, or only the given provider's models.
func (*ModelRuntime) GetModelsOfType ¶
func (runtime *ModelRuntime) GetModelsOfType(modelType ai.ModelType, providerID ...string) []ai.AnyModel
GetModelsOfType lists the last-known models of one type from one provider or all providers.
func (*ModelRuntime) GetPhysicalModel ¶
func (runtime *ModelRuntime) GetPhysicalModel(provider, id string) *ai.Model
GetPhysicalModel returns a catalog chat model that is not virtual, or nil.
upstream: model-runtime.ts:1015-1018 (getPhysicalModel)
func (*ModelRuntime) GetProvider ¶
func (runtime *ModelRuntime) GetProvider(id string) *ai.ModelsProvider
GetProvider 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.
func (*ModelRuntime) GetProviderAuthStatus ¶
func (runtime *ModelRuntime) GetProviderAuthStatus(providerID string) ai.AuthStatus
GetProviderAuthStatus uses the published availability snapshot for stored credentials. A stale operation cannot reintroduce deleted credential metadata.
func (*ModelRuntime) GetProviders ¶
func (runtime *ModelRuntime) GetProviders() []*ai.ModelsProvider
GetProviders lists every composed provider in provider order.
func (*ModelRuntime) GetRegisteredNativeProvider ¶
func (runtime *ModelRuntime) GetRegisteredNativeProvider(providerID string) *ai.ModelsProvider
GetRegisteredNativeProvider returns the original native registration of a provider, or nil.
func (*ModelRuntime) GetRegisteredProviderConfig ¶
func (runtime *ModelRuntime) GetRegisteredProviderConfig(providerID string) *ProviderConfigInput
GetRegisteredProviderConfig returns the active provider registration input, or nil.
func (*ModelRuntime) GetRegisteredProviderIds ¶
func (runtime *ModelRuntime) GetRegisteredProviderIds() []string
GetRegisteredProviderIds lists the IDs of the providers registered through RegisterProvider or RegisterNativeProvider.
func (*ModelRuntime) HasConfiguredAuth ¶
func (runtime *ModelRuntime) HasConfiguredAuth(providerID string) bool
HasConfiguredAuth is Pi's ModelRuntime.hasConfiguredAuth: providerID is in the published availability snapshot's configured set, without credential I/O. A credential written or removed after a pass is seen once a pass or a credential operation's synchronization publishes it. A provider of only virtual models needs no credentials, so it is configured.
upstream: model-runtime.ts:543-545 (hasConfiguredAuth), 953-958 (a provider of only virtual models is configured at registration)
func (*ModelRuntime) IsUsingOAuth ¶
func (runtime *ModelRuntime) IsUsingOAuth(providerID string) bool
IsUsingOAuth reports the auth type in the latest published availability snapshot.
func (*ModelRuntime) IsUsingSubscription ¶
func (runtime *ModelRuntime) IsUsingSubscription(providerID string) bool
IsUsingSubscription requires both published OAuth usage and the provider's current subscription metadata.
func (*ModelRuntime) ListCredentials ¶
func (runtime *ModelRuntime) ListCredentials(ctx context.Context) ([]ai.CredentialInfo, error)
ListCredentials enumerates the runtime overlay and shared credential storage.
func (*ModelRuntime) Login ¶
func (runtime *ModelRuntime) Login(ctx context.Context, id string, kind ai.AuthType, interaction ai.AuthInteraction, options ...ai.LoginOptions) (ai.Credential, error)
Login awaits same-provider credential operations, authentication by the auth methods of the composed provider GetProvider returns for the ID, and local synchronization. Optional LoginOptions reach the provider's OAuth login, as Pi's login(providerId, type, interaction, options) does (model-runtime.ts:817-825). A committed login whose synchronization fails returns CredentialSynchronizationError.
func (*ModelRuntime) Logout ¶
func (runtime *ModelRuntime) Logout(ctx context.Context, id string) error
Logout awaits same-provider credential operations before deleting credentials and synchronizing local models. A committed deletion whose synchronization fails returns CredentialSynchronizationError.
func (*ModelRuntime) Refresh ¶
func (runtime *ModelRuntime) Refresh(ctx context.Context, options ...ai.ModelsRefreshOptions) ai.ModelsRefreshResult
Refresh first yields to the queued registration refresh (model-runtime.ts:750,788,796), then awaits provider-owned catalog publication and generation-checked availability reconciliation. A full refresh recomposes every provider and so supersedes their in-flight refreshes.
func (*ModelRuntime) RegisterNativeProvider ¶
func (runtime *ModelRuntime) RegisterNativeProvider(provider *ai.ModelsProvider) error
RegisterNativeProvider installs a provider-owned catalog, auth and API implementation.
func (*ModelRuntime) RegisterProvider ¶
func (runtime *ModelRuntime) RegisterProvider(id string, input ProviderConfigInput) error
RegisterProvider composes legacy provider callbacks with models.json and native registrations.
func (*ModelRuntime) RegisterVirtualModel ¶
func (runtime *ModelRuntime) RegisterVirtualModel(definition VirtualModelDefinition) error
RegisterVirtualModel registers a virtual model under definition.Provider, which may also list physical models or several virtual models. Re-registering the same provider and id replaces the virtual model. It fails when the id belongs to a physical model of that provider.
upstream: model-runtime.ts:938-960 (registerVirtualModel)
func (*ModelRuntime) RemoveRuntimeApiKey ¶
func (runtime *ModelRuntime) RemoveRuntimeApiKey(ctx context.Context, providerID string) error
RemoveRuntimeApiKey drops the non-persistent API key of a provider, serialized with the provider's other credential operations and followed by local synchronization.
func (*ModelRuntime) ResolveModel ¶
func (runtime *ModelRuntime) ResolveModel(ctx context.Context, model *ai.Model, messages []ai.Message, options ResolveModelOptions) (ModelRoute, error)
ResolveModel asks a virtual model's router for the model and thinking level of one request. The router must return a physical catalog model whose provider has credentials; the thinking level is clamped to that model. It fails when routing fails.
Previous reports the latest successful response in messages. A retry passes the failed response as options.Failed; messages no longer contains it.
upstream: model-runtime.ts:973-1012 (resolveModel)
func (*ModelRuntime) RuntimeModels ¶
func (runtime *ModelRuntime) RuntimeModels() []icodingagent.RuntimeModel
RuntimeModels returns the selection metadata of the composed catalog: the registry's models with the registered virtual models added after each provider's physical models, or after every provider for a provider of only virtual models. A virtual model hides a physical chat model with the same id. Startup model resolution reads it, so `--model`, the saved default and the `--models` scope can name a virtual model.
upstream: model-runtime.ts:285-293 (provider list with virtual models), virtual-models.ts:190-227 (withVirtualModels)
func (*ModelRuntime) SetChangeListener ¶
func (runtime *ModelRuntime) SetChangeListener(listener func()) func()
SetChangeListener replaces the callback invoked after committed registry changes and returns a draining detach function.
func (*ModelRuntime) SetRuntimeApiKey ¶
func (runtime *ModelRuntime) SetRuntimeApiKey(ctx context.Context, providerID, apiKey string) error
SetRuntimeApiKey installs a non-persistent API key for a provider, serialized with the provider's other credential operations and followed by local synchronization. A synchronization failure returns CredentialSynchronizationError.
func (*ModelRuntime) Stream ¶
func (runtime *ModelRuntime) Stream(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
Stream returns immediately. Context normalization happens before asynchronous setup. Setup failures are errors; provider cancellation is aborted, and an established stream owns its terminal event.
func (*ModelRuntime) StreamDeferred ¶
func (runtime *ModelRuntime) StreamDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, options ...ai.DeferredFetchOptions) *ai.AssistantMessageEventStream
StreamDeferred forwards the selected model, handle and optional request overrides through the same native model collection as FetchDeferred. A model of a provider an extension registered goes to that provider object's fetchDeferred after the same request authentication its stream gets. upstream: packages/ai/src/models.ts:StreamDeferred
func (*ModelRuntime) StreamSimple ¶
func (runtime *ModelRuntime) StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, options ...ai.StreamOptions) *ai.AssistantMessageEventStream
StreamSimple shares normalization and auth preparation with Stream; options is optional, as in pi-ai. Native and caller-owned callbacks receive source options; only registry-built stock API leaves lower simple options.
func (*ModelRuntime) UnregisterProvider ¶
func (runtime *ModelRuntime) UnregisterProvider(providerID string)
UnregisterProvider removes a provider registration, native or legacy, and queues the local refresh. An unknown ID is not an error.
func (*ModelRuntime) UnregisterVirtualModel ¶
func (runtime *ModelRuntime) UnregisterVirtualModel(provider, id string)
UnregisterVirtualModel removes a virtual model. An unknown provider or id is ignored.
upstream: model-runtime.ts:963-970 (unregisterVirtualModel)
type ModelScopeDiagnostic ¶
type ModelScopeDiagnostic = icodingagent.ModelScopeDiagnostic
ModelScopeDiagnostic identifies a scope pattern that did not resolve cleanly (model-resolver.ts ResolveModelScopeResult.diagnostics).
type ModelSelection ¶
ModelSelection names a model by provider and id. Provider and ModelID hold what JavaScript's String() gives the entry's members, as a template literal prints them. Unresolvable is set when either member is not a string: the selection names no catalog model and a lookup finds nothing.
func GetBranchSelection ¶
func GetBranchSelection(branch []icodingagent.SessionEntry, getModel func(provider, modelID string) *ai.Model) *ModelSelection
GetBranchSelection returns the model selection a session branch records, or nil. A virtual `model_change` holds until the next `model_change`, because responses name the physical models it routed to. Otherwise the latest physical response wins, as in sessions without virtual models. A virtual model that is no longer registered does not hold, so the selection falls back to the physical model that answered last.
Only the last `model_change` can hold, so this looks up at most one model in the catalog.
upstream: virtual-models.ts:126-157 (getBranchSelection, findLastModelChange)
type NavigateTreeOptions ¶
type NavigateTreeOptions struct {
// left before navigating. Mirrors upstream navigateTree summarize flag.
Summarize bool
CustomInstructions string
// default summary prompt instead of being appended to it.
ReplaceInstructions bool
// when no summary is created.
Label string
}
NavigateTreeOptions controls Session.NavigateTree behaviour.
type NavigateTreeResult ¶
type NavigateTreeResult struct {
// nil when none was created.
SummaryEntry *BranchSummaryEntry
}
NavigateTreeResult is the return value of Session.NavigateTree.
type NestedCallRecorder ¶
type NestedCallRecorder struct {
// contains filtered or unexported fields
}
NestedCallRecorder collects the nested calls of one model-issued tool call, including calls made by nested tools. Its snapshot becomes `nestedCalls` on the tool result message. It is safe for concurrent use.
upstream: nested-tool-calls.ts:47-101 (NestedCallRecorder)
func NewNestedCallRecorder ¶
func NewNestedCallRecorder() *NestedCallRecorder
NewNestedCallRecorder returns an empty, complete recorder.
func (*NestedCallRecorder) AddUsage ¶
func (r *NestedCallRecorder) AddUsage(usage ai.Usage)
AddUsage adds the usage of a nested result, including for calls dropped from the record.
upstream: nested-tool-calls.ts:87-89
func (*NestedCallRecorder) Finish ¶
func (r *NestedCallRecorder) Finish(record *ai.NestedToolCallRecord, isError bool, errorText string)
Finish sets the status, duration and truncated error text of a record Start returned. A nil record is ignored.
upstream: nested-tool-calls.ts:79-85
func (*NestedCallRecorder) Snapshot ¶
func (r *NestedCallRecorder) Snapshot() *ai.NestedToolCalls
Snapshot returns a copy of the record so far, or nil when no nested call was made.
upstream: nested-tool-calls.ts:95-100
func (*NestedCallRecorder) Start ¶
func (r *NestedCallRecorder) Start(toolCall agent.AgentToolCall) *ai.NestedToolCallRecord
Start records a call as it starts. It returns nil when the call is dropped.
upstream: nested-tool-calls.ts:56-77
func (*NestedCallRecorder) TotalUsage ¶
func (r *NestedCallRecorder) TotalUsage() *ai.Usage
TotalUsage returns the summed usage of every nested result, or nil when none reported usage.
upstream: nested-tool-calls.ts:91-93
type NestedCallSummary ¶
type NestedCallSummary struct {
// Calls becomes `nestedCalls`. Nil when no nested call was made.
Calls *ai.NestedToolCalls
// Usage is the summed usage of the nested results, added to the message's usage.
Usage *ai.Usage
}
NestedCallSummary is what the nested calls of one model-issued tool call leave on its tool result message.
upstream: nested-tool-calls.ts:36-41 (NestedCallSummary)
type NestedToolCallHost ¶
type NestedToolCallHost interface {
// GetTools returns the tools nested calls resolve against.
GetTools() []agent.AgentTool
// IsSequential reports whether every nested call runs exclusively, as when the agent executes tool calls sequentially.
IsSequential() bool
// RunToolCall runs the call through the tool pipeline, with hooks that report parentToolCallID. onUpdate forwards partial results. It returns onUpdate's first error, as upstream's runToolCall rejects, and then the hooks have not run.
RunToolCall(ctx context.Context, toolCall agent.AgentToolCall, parentToolCallID string, onUpdate agent.ToolUpdateSink) (agent.AgentToolCallOutcome, error)
// Emit publishes a `tool_execution_*` event of a nested call. Its ParentToolCallID is set.
Emit(event agent.AgentEvent)
}
NestedToolCallHost is what the runner needs from its session.
upstream: nested-tool-calls.ts:130-143 (NestedToolCallHost)
type NestedToolCallOptions ¶
type NestedToolCallOptions struct {
// OnUpdate receives partial results of the nested tool, in addition to `tool_execution_update` events. An error is the callback's throw: that update raises no `tool_execution_update` event and the call rejects with the first error.
OnUpdate agent.ToolUpdateSink
}
NestedToolCallOptions are the options of one nested call. The call's cancellation is the context passed to NestedToolCallRunner.Execute.
upstream: nested-tool-calls.ts:103-108 (NestedToolCallOptions)
type NestedToolCallRunner ¶
type NestedToolCallRunner struct {
// contains filtered or unexported fields
}
NestedToolCallRunner runs the tool calls that a tool makes while it runs (`ctx.executeTool()`), for example from codemode scripts. The agent loop does not know about them: the session runs each one through the agent's tool pipeline with its own hooks, emits `tool_execution_*` events with ParentToolCallID, and records the calls and their usage on the model-issued call's tool result message. Nothing here runs until a tool calls `ctx.executeTool()`.
upstream: nested-tool-calls.ts:160-261 (NestedToolCallRunner)
func NewNestedToolCallRunner ¶
func NewNestedToolCallRunner(host NestedToolCallHost) *NestedToolCallRunner
NewNestedToolCallRunner returns a runner over host.
func (*NestedToolCallRunner) Clear ¶
func (r *NestedToolCallRunner) Clear()
Clear drops every scope. The session calls it when the agent run ends.
upstream: nested-tool-calls.ts:258-260 (clear)
func (*NestedToolCallRunner) Execute ¶
func (r *NestedToolCallRunner) Execute(ctx context.Context, callerID, name string, args json.RawMessage, options NestedToolCallOptions) (agent.AgentToolCallOutcome, error)
Execute runs name on behalf of the call callerID. The nested call gets the id `<callerID>/<n>`. It never fails for tool failures: they come back as an outcome with IsError set. It returns the first error of options.OnUpdate, as upstream's promise rejects; the call then records no result and emits no `tool_execution_end`. args must be a JSON object; null or empty arguments are `{}`.
upstream: nested-tool-calls.ts:171-248 (execute)
func (*NestedToolCallRunner) TakeRecord ¶
func (r *NestedToolCallRunner) TakeRecord(toolCallID string) *NestedCallSummary
TakeRecord removes and returns the record of the nested calls a model-issued call made, or nil when it made none.
upstream: nested-tool-calls.ts:250-256 (takeRecord)
type PreparedPrompt ¶
type PreparedPrompt struct {
// contains filtered or unexported fields
}
PreparedPrompt holds one prompt's preflight result. It does not reserve the agent or mutate another prompt's pending messages while an extension awaits input.
func (*PreparedPrompt) NormalizeImages ¶
func (p *PreparedPrompt) NormalizeImages()
NormalizeImages applies the image profile of the limits model (the physical model of the latest virtual-selection response, else the selected model) after before_agent_start has completed (agent-session.ts:2037). It is the last step of the preparation, so it also takes the pending nextTurn messages for the run, as _prepareRun does after it normalizes the images (agent-session.ts:1914-1925). The held messages are flushed after that (:1852-1853), so a nextTurn message queued while they are emitted, such as one a Session listener sends, waits for the next run.
type PreparedPromptRun ¶
type PreparedPromptRun struct {
// contains filtered or unexported fields
}
PreparedPromptRun owns an admitted Session prompt across its first event and the remainder of execution.
func (*PreparedPromptRun) Run ¶
func (r *PreparedPromptRun) Run() ([]agent.AgentMessage, error)
Run completes execution, recovery and settlement and releases the admitted run.
func (*PreparedPromptRun) Start ¶
func (r *PreparedPromptRun) Start() error
Start dispatches agent_start without waiting for the Provider. Run must follow exactly once, even after Start fails.
type PromptDisposition ¶
type PromptDisposition = QueuedInputDisposition
PromptDisposition is how Prompt dealt with an accepted input: an extension command or input handler consumed it (`handled`), it was queued behind a running turn (`queued`), or a turn started (`started`).
upstream: agent-session.ts:290 (PromptDisposition)
type PromptOptions ¶
type PromptOptions struct {
ExpandPromptTemplates *bool
Images []ai.ImageContent
StreamingBehavior extension.DeliverAs
Source extension.InputSource
// PreflightResult observes how an accepted prompt was dispatched. It is not called when the prompt is rejected.
//
// upstream: agent-session.ts:302-303 (PromptOptions.preflightResult)
PreflightResult func(PromptDisposition)
}
PromptOptions controls one invocation, independently of the Session's system-prompt construction inputs.
type PromptTemplate ¶
type PromptTemplate = icodingagent.PromptTemplate
PromptTemplate is a resolved file-based prompt template.
type PromptsResult ¶
type PromptsResult struct {
Prompts []PromptTemplate
Diagnostics []extension.ResourceDiagnostic
}
PromptsResult is a loader's prompt templates with the diagnostics found while resolving them.
type ProviderConfigInput ¶
type ProviderConfigInput = icodingagent.ProviderConfigInput
type QueueInputOptions ¶
type QueueInputOptions struct {
Source extension.InputSource
}
QueueInputOptions supplies the input source for a direct queue operation.
type QueuedInputDisposition ¶
type QueuedInputDisposition string
QueuedInputDisposition is how Steer and FollowUp dealt with their input: an input handler consumed it (`handled`) or it was queued (`queued`).
upstream: agent-session.ts:289 (QueuedInputDisposition)
type QuietStartup ¶
type QuietStartup = icodingagent.QuietStartup
QuietStartup is the quiet startup setting (re-exported alias): true hides all startup output, "header" keeps only the startup header.
type ReloadOption ¶
type ReloadOption func(*reloadOptions)
ReloadOption configures Session.Reload (agent-session.ts reload(options)).
func WithBeforeSessionStart ¶
func WithBeforeSessionStart(fn func(context.Context) error) ReloadOption
WithBeforeSessionStart runs fn after the new runner is bound and before it receives session_start, only when the mode bound its UI or command actions (reload's options.beforeSessionStart, agent-session.ts:3676-3678). An error from fn fails the reload.
type ResolveCliModelOptions ¶
type ResolveCliModelOptions struct {
CliProvider string
CliModel string
CliThinking ai.ThinkingLevel
// InlineApiKey is --api-key supplied for the selected provider.
InlineApiKey bool
ModelRuntime *ModelRuntime
}
ResolveCliModelOptions are the options of ResolveCliModel (model-resolver.ts resolveCliModel options).
type ResolveCliModelResult ¶
type ResolveCliModelResult struct {
Model *ai.Model
ThinkingLevel ai.ThinkingLevel
Warning string
// Error is a message suitable for CLI display.
Error string
}
ResolveCliModelResult is a CLI model selection (model-resolver.ts ResolveCliModelResult). When Error is set, Model is nil.
func ResolveCliModel ¶
func ResolveCliModel(options ResolveCliModelOptions) ResolveCliModelResult
ResolveCliModel resolves one model from CLI flags against every catalog model, not only those with configured auth, so `--api-key` works for first-time setup. It parses a "<pattern>:<thinking>" suffix and returns the level without applying it. upstream: model-resolver.ts:406 (resolveCliModel)
type ResolveModelOptions ¶
type ResolveModelOptions struct {
Reason ModelRouteReason
ThinkingLevel ai.ModelThinkingLevel
// Failed is the failed response of a retry; the messages no longer contain it.
Failed *ai.AssistantMessage
// State is the router state the caller stored; the caller also stores the returned state.
State json.RawMessage
}
ResolveModelOptions are the options of ModelRuntime.ResolveModel.
type ResolveModelScopeResult ¶
type ResolveModelScopeResult struct {
ScopedModels []ScopedModel
Diagnostics []ModelScopeDiagnostic
}
ResolveModelScopeResult is the resolved scope in pattern order and its diagnostics (model-resolver.ts ResolveModelScopeResult).
func ResolveModelScopeWithDiagnostics ¶
func ResolveModelScopeWithDiagnostics(ctx context.Context, patterns []string, runtime *ModelRuntime) (ResolveModelScopeResult, error)
ResolveModelScopeWithDiagnostics resolves scope patterns against the runtime's available models and returns the diagnostics with the scope. A GetAvailable failure is returned unchanged. upstream: model-resolver.ts:364 (resolveModelScopeWithDiagnostics)
type ResolveProjectTrustInput ¶
type ResolveProjectTrustInput struct {
// ExtensionsResult is the bootstrap extension set, loaded with the project untrusted (resource-loader.ts loadProjectTrustExtensions).
ExtensionsResult LoadExtensionsResult
}
ResolveProjectTrustInput is the argument of ResourceLoaderReloadOptions.ResolveProjectTrust.
type ResolvedRequestAuth ¶
type ResolvedRequestAuth = extension.ResolvedRequestAuth
ResolvedRequestAuth is the compatibility result for a model's request credentials (model-registry.ts:33).
type ResourceExtensionPaths ¶
type ResourceExtensionPaths struct {
SkillPaths []ExtensionResourcePath
PromptPaths []ExtensionResourcePath
ThemePaths []ExtensionResourcePath
}
ResourceExtensionPaths are the resource paths extensions contribute (resource-loader.ts ResourceExtensionPaths).
type ResourceLoader ¶
type ResourceLoader interface {
GetSkills() SkillsResult
GetPrompts() PromptsResult
GetAgentsFiles() AgentsFilesResult
// GetSystemPrompt returns the system prompt text that replaces the default prompt, and whether the loader has one.
GetSystemPrompt() (string, bool)
// GetAppendSystemPrompt returns the texts appended to the system prompt.
GetAppendSystemPrompt() []string
// GetSystemPromptSource returns the file the system prompt was read from, and whether it came from a file.
GetSystemPromptSource() (ResourceSource, bool)
// GetAppendSystemPromptSources returns the files the appended texts were read from, in order.
GetAppendSystemPromptSources() []ResourceSource
// GetExtensions returns the extensions the last Reload found (resource-loader.ts getExtensions).
GetExtensions() LoadExtensionsResult
// GetThemes returns the themes the last Reload and ExtendResources found (resource-loader.ts getThemes).
GetThemes() ThemesResult
// ExtendResources adds the skills, prompt templates and themes extensions contributed (resource-loader.ts extendResources).
ExtendResources(paths ResourceExtensionPaths) error
// Reload rediscovers every resource (resource-loader.ts reload).
Reload(options ...ResourceLoaderReloadOptions) error
}
ResourceLoader supplies the resolved resources a Session reads while it runs. A Session reads the loader on every use, so a loader that reloads is observed by the next prompt and the next system prompt rebuild. It carries the skills, prompt templates, context files and system prompt text a Session consumes (resource-loader.ts ResourceLoader); the Extension Host, themes and extension resources are owned elsewhere in PiG.
var NoResources ResourceLoader = &staticResourceLoader{}
NoResources is a ResourceLoader with no resources. A caller that expands resources and builds its system prompt itself supplies it so the Session neither discovers, expands nor renders any.
type ResourceLoaderReloadOptions ¶
type ResourceLoaderReloadOptions struct {
// ResolveProjectTrust decides whether the project is trusted before any resource loads; the loader applies the answer to its settings.
ResolveProjectTrust func(ctx context.Context, input ResolveProjectTrustInput) (bool, error)
}
ResourceLoaderReloadOptions are the options of DefaultResourceLoader.Reload (resource-loader.ts ResourceLoaderReloadOptions).
type ResourceSource ¶
type ResourceSource struct {
Path string
}
ResourceSource names the file a loaded resource came from (resource-loader.ts { path: string }).
type RoutedModel ¶
type RoutedModel struct {
Model *ai.Model
ThinkingLevel ai.ModelThinkingLevel
}
RoutedModel is the physical model and thinking level a virtual selection currently resolves to.
type RunStart ¶
type RunStart struct {
// contains filtered or unexported fields
}
RunStart is a run that counts as busy from its start (agent-session.ts:1826-1849 _startRun). While its compaction check and before_agent_start handlers run, the Session is streaming, so a message sent meanwhile joins the run and a prompt must name its streamingBehavior; bash results and custom messages wait for the run; and an abort requested meanwhile aborts the run at agent_start. It ends when the Agent claims the run, or with Abandon.
func (*RunStart) Abandon ¶
func (r *RunStart) Abandon()
Abandon ends a start that failed before the Agent claimed its run (agent-session.ts:1838-1843, _startRun's catch): the Session returns to idle, what was held for the run is appended and idle waiters wake. A run that claimed the Session since then keeps its state.
func (*RunStart) FlushHeldMessages ¶
FlushHeldMessages appends the bash results and custom messages held while the run was starting before its starting messages (agent-session.ts:1845-1848). No run exists yet, so they cannot split a tool call from its result. It reports whether it appended custom messages, whose message_start and message_end events precede preflightResult("started").
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime constructs Sessions and, when created with CreateAgentSessionRuntime, owns replacement through the retained cwd-bound factory.
func CreateAgentSessionRuntime ¶
func CreateAgentSessionRuntime(ctx context.Context, factory CreateAgentSessionRuntimeFactory, options CreateAgentSessionRuntimeOptions) (*Runtime, error)
CreateAgentSessionRuntime constructs the first Session and retains the same factory for later replacements. The caller binds extensions after subscribing to Session events. upstream: agent-session-runtime.ts:426-438 (createAgentSessionRuntime: assert the cwd, run the factory, construct the AgentSessionRuntime over its result).
func NewAgentSessionRuntime ¶
func NewAgentSessionRuntime(ctx context.Context, session *Session, services *AgentSessionServices, createRuntime CreateAgentSessionRuntimeFactory, diagnostics []AgentSessionRuntimeDiagnostic, modelFallbackMessage string) (*Runtime, error)
NewAgentSessionRuntime is upstream's `new AgentSessionRuntime(session, services, createRuntime, diagnostics, modelFallbackMessage)` (agent-session-runtime.ts:81-93): a Runtime that owns the given Session and its Services and retains createRuntime for later replacements. The Session must be the one constructed over services. ctx bounds the Runtime's own cancellation signal, as a Go call bounds it; upstream's constructor has no such input.
func NewRuntime ¶
func NewRuntime(opts RuntimeOptions) (*Runtime, error)
NewRuntime constructs a Runtime.
func (*Runtime) Close ¶
Close releases Runtime-level resources. Services supplied by the caller remain caller-owned and must be closed separately.
func (*Runtime) Continue ¶
func (rt *Runtime) Continue(opts SessionStartOptions) (*Session, error)
Continue resumes the most-recent Session.
func (*Runtime) Diagnostics ¶
func (rt *Runtime) Diagnostics() []AgentSessionRuntimeDiagnostic
Diagnostics returns the diagnostics of the current construction; a replacement's own replace them. upstream: agent-session-runtime.ts get diagnostics, apply
func (*Runtime) EmitQuitShutdown ¶
func (rt *Runtime) EmitQuitShutdown()
EmitQuitShutdown emits session_shutdown with reason quit for the current Session, once. A mode that must emit it before it tears its terminal down calls it; Close then does not repeat the event.
func (*Runtime) EmitQuitShutdownContext ¶
EmitQuitShutdownContext is EmitQuitShutdown with the context that dispatches the event to extensions, for a mode that awaits its handlers' acknowledgement.
func (*Runtime) ExtensionCommandActions ¶
func (rt *Runtime) ExtensionCommandActions(session *Session) extension.CommandActions
ExtensionCommandActions returns session's command-context actions with new, fork and switch replaced by the Runtime's replacement path, as Pi's print, RPC and interactive modes bind newSession, fork and switchSession to the runtime host. The other actions stay bound to session.
func (*Runtime) ExtensionContext ¶
func (rt *Runtime) ExtensionContext() *icodingagent.ExtensionContext
ExtensionContext returns the shared extension context.
func (*Runtime) Fork ¶
func (rt *Runtime) Fork(ctx context.Context, entryID string, options *extension.ForkOptions) (RuntimeForkResult, error)
func (*Runtime) ImportFromJsonl ¶
func (rt *Runtime) ImportFromJsonl(ctx context.Context, input string, cwdOverride ...string) (extension.CancelledResult, error)
ImportFromJsonl copies an external log without overwriting an existing same-name Session, then replaces the active runtime. A non-empty cwdOverride replaces a stored working directory that no longer exists.
func (*Runtime) ListSessions ¶
func (rt *Runtime) ListSessions() ([]SessionInfo, error)
ListSessions returns SessionInfo summaries.
func (*Runtime) ModelFallbackMessage ¶
ModelFallbackMessage returns the model fallback message of the current construction; a replacement's own replaces it. upstream: agent-session-runtime.ts get modelFallbackMessage, apply
func (*Runtime) New ¶
func (rt *Runtime) New(opts SessionStartOptions) (*Session, error)
New creates a fresh Session.
func (*Runtime) NewExtensionRunner ¶
NewExtensionRunner returns the extension runner.
func (*Runtime) NewSession ¶
func (rt *Runtime) NewSession(ctx context.Context, options *extension.NewSessionOptions) (extension.CancelledResult, error)
NewSession tears down the outgoing Session and creates a fresh Session through the retained factory. Cancellation precedes all replacement work.
func (*Runtime) Open ¶
func (rt *Runtime) Open(path string, opts SessionStartOptions) (*Session, error)
Open loads an existing Session by path.
func (*Runtime) Resume ¶
func (rt *Runtime) Resume(id string, opts SessionStartOptions) (*Session, error)
Resume loads an existing Session by id.
func (*Runtime) Services ¶
func (rt *Runtime) Services() *AgentSessionServices
Services returns the underlying dependency container.
func (*Runtime) Session ¶
Session returns the current factory-owned Session, or nil before a low-level Runtime has constructed one.
func (*Runtime) SetBeforeSessionInvalidate ¶
func (rt *Runtime) SetBeforeSessionInvalidate(fn func())
SetBeforeSessionInvalidate installs a synchronous teardown hook that runs before the runner is invalidated.
func (*Runtime) SetBeforeSessionReplacement ¶
SetBeforeSessionReplacement installs the mode's awaited drain. It runs once a replacement is approved and before the outgoing Session aborts, so a mode can release queued input or join its own work. Configure it before starting replacement operations.
func (*Runtime) SetRebindSession ¶
SetRebindSession installs the awaited host rebind callback. Configure it before starting replacement operations.
func (*Runtime) SetReload ¶
SetReload installs the mode's reload of the current Session: the work of upstream's session.reload() that depends on the resources and extension host the mode owns. Configure it before extensions run.
func (*Runtime) SwitchSession ¶
func (rt *Runtime) SwitchSession(ctx context.Context, path string, options ...*SwitchSessionOptions) (extension.CancelledResult, error)
SwitchSession loads and validates the destination before disposing the outgoing Session, then rebuilds its cwd-bound runtime (agent-session-runtime.ts:196-222).
func (*Runtime) ValidateSwitchSession ¶
ValidateSwitchSession reports the error that switching to path would return from loading it, without running any handler or replacing anything. Pi's switchSession raises it before it waits for any replacement ahead of it. The loaded Session is discarded.
type RuntimeForkResult ¶
type RuntimeForkResult struct {
Cancelled bool `json:"cancelled"`
SelectedText *string `json:"selectedText,omitempty"`
}
RuntimeForkResult retains selectedText presence: it is absent for position at and for a cancelled fork.
type RuntimeOptions ¶
type RuntimeOptions struct {
// Services is the dependency container produced by CreateAgentSessionServices.
// Required.
Services *AgentSessionServices
// NewExtensions are the extensions (`coding/extension`) to pre-load.
// Their tools layer into every Session created by this Runtime.
NewExtensions []extension.Extension
// ExtensionRuntime is the registration state the extension host that loaded NewExtensions already holds (MCP servers,
// providers, virtual models). The Session's runner shares it, so a registration by an out-of-process extension reaches
// the runner's `mcp_servers_change` dispatch and `getMcpServers`. Nil gives the runner its own state.
ExtensionRuntime *extension.ExtensionRuntime
// AbortContext is the parent context for the runtime's own
// cancellation signals. If nil, context.Background() is used.
AbortContext context.Context
// ExtensionHost is the extension host that loaded NewExtensions. Every Session the Runtime creates returns it from [Session.ExtensionHost]. Nil: the Sessions have none.
ExtensionHost ExtensionHost
}
RuntimeOptions configures Runtime construction.
type ScopedModel ¶
type ScopedModel = extension.ScopedModel
Ports packages/coding-agent/src/core/agent-session.ts. ScopedModel pairs a native cycling model with its optional thinking preference.
func ResolveModelScope ¶
func ResolveModelScope(ctx context.Context, patterns []string, runtime *ModelRuntime) ([]ScopedModel, error)
ResolveModelScope is ResolveModelScopeWithDiagnostics that writes each diagnostic to stderr as a yellow "Warning: " line and returns only the scope. upstream: model-resolver.ts:372-382 (resolveModelScope)
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is an active agent runtime: one JSONL on disk, one agent.Agent in memory, plus the tools+hooks the caller configured. Mirrors upstream pi-coding-agent's AgentSession.
A Session is mutable: Send appends messages, Fork moves the leaf, Close releases resources. Methods may be called from any goroutine, but Send itself is single-threaded with respect to the underlying agent loop: concurrent Sends serialise via an internal mutex.
Construct a Session via NewSession or through Runtime.
func NewAgentSession ¶
func NewAgentSession(config SessionOptions) (*Session, error)
NewAgentSession is upstream's `new AgentSession(config)`: the Session for config, built against config.Services. A nil UsesDefaultTools is false, as the constructor reads it; NewSession derives it as createAgentSession does. upstream: agent-session.ts:485 constructor(config: AgentSessionConfig), agent-session.ts:500 `config.usesDefaultTools ?? false`
func NewSession ¶
func NewSession(svcs *AgentSessionServices, opts SessionOptions) (*Session, error)
NewSession constructs an active session against the given Services container. It uses SessionManager directly when supplied; otherwise it creates a fresh log or opens ResumePath. Supplied history restores model and thinking before capability clamping. Explicit thinking wins; history without thinking metadata uses the global default and records the selected level.
Errors:
- svcs is nil → ErrNoServices
- opts.Model is nil → restore the selected model from supplied or resumed history when available; otherwise start without a selected model.
- file persistence fails → wrapped error
- ResumePath set and the file is missing/corrupt → wrapped error
func (*Session) Abort ¶
Abort cancels the active run, whoever started it, and waits until the session is idle (upstream abort).
func (*Session) AbortBash ¶
func (s *Session) AbortBash()
AbortBash cancels every in-flight ExecuteBash call. Mirrors upstream abortBash.
func (*Session) AbortBranchSummary ¶
func (s *Session) AbortBranchSummary()
AbortBranchSummary cancels an in-flight branch-summary LLM call within NavigateTree. Safe to call when no summary is running. Mirrors upstream abortBranchSummary().
func (*Session) AbortCompaction ¶
func (s *Session) AbortCompaction()
AbortCompaction cancels an in-flight Compact() call. Safe to call when no compaction is running (no-op). Mirrors upstream abortCompaction().
func (*Session) AbortRetry ¶
func (s *Session) AbortRetry()
AbortRetry cancels an active automatic-retry delay without cancelling the current Session.
func (*Session) ActiveToolNames ¶
ActiveToolNames returns the names of the tools active for the next agent turn. Mirrors upstream AgentSession.getActiveToolNames.
func (*Session) Agent ¶
Agent returns the underlying *agent.Agent. agent is a public package so SDK consumers can use this to inspect timings, hooks, and in-memory state. Mutating the agent's tool/hook lists after Send has been called is undefined.
func (*Session) AgentRunAbortRequested ¶
AgentRunAbortRequested is upstream _agentRunAbortRequested: whether abort was requested while the current run was active. A new run clears it.
func (*Session) AppendCustomEntry ¶
AppendCustomEntry records extension-owned data as a custom entry on the active branch and reports it as an `entry_appended` event, like the entries the core appends for its own state. It is the session behind upstream's `pi.appendEntry()`, for built-in extensions that reach the session through `ctx.sessionManager`.
upstream: agent-session.ts (appendCustomEntry through the extension runner's appendEntry action)
func (*Session) AutoCompactionEnabled ¶
AutoCompactionEnabled reports the global compaction setting (agent-session.ts get autoCompactionEnabled).
func (*Session) AutoRetryEnabled ¶
AutoRetryEnabled reports the global retry setting (agent-session.ts get autoRetryEnabled).
func (*Session) AvailableModelSnapshot ¶
AvailableModelSnapshot returns the Session ModelRuntime's available models, each bound to its backend. Scope entries must come from it: a catalog descriptor carries no backend, so a model cycled to from such an entry fails prompt validation with agent.ErrNoModelSelected. upstream: packages/coding-agent/src/modes/interactive/interactive-mode.ts:showModelsSelector (this.session.modelRuntime.getAvailableSnapshot())
func (*Session) AvailableThinkingLevels ¶
func (s *Session) AvailableThinkingLevels() []ai.ModelThinkingLevel
AvailableThinkingLevels returns the levels supported by the current model.
func (*Session) BeginModelChange ¶
func (s *Session) BeginModelChange(ctx context.Context, m *ai.Model, source extension.ModelSelectSource, options ...ModelMutationOptions) (func(), error)
BeginModelChange applies the synchronous model mutation and returns its awaited extension notification, or nil when it is already complete. RPC admits the next command after this prefix; blocking SDK callers invoke a non-nil completion before returning. The caller owns and joins completion, which must be invoked once.
func (*Session) BeginModelCycle ¶
func (s *Session) BeginModelCycle(ctx context.Context, direction string, options ...ModelMutationOptions) (*ModelCycleResult, func(), error)
BeginModelCycle is Session.CycleModel split at its await: it applies the model and thinking change, returns the result, and returns the model_select notification as a completion the caller invokes once, or nil when none is pending. RPC admits its next command after this prefix. A nil result means there is nothing to cycle to.
func (*Session) BeginModelCycleOnMain ¶
func (s *Session) BeginModelCycleOnMain(ctx context.Context, direction string, options ModelMutationOptions) (*ModelCycleResult, func(), error)
BeginModelCycleOnMain is Session.BeginModelCycle for an owner loop, as Session.SetModelOnMain is for SetModel: the model and thinking change apply on the caller, and the completion runs the thinking_level_select and model_select notifications, which admit extension handlers and must not run on the loop. The completion then records in the result the thinking level a handler left (agent-session.ts:2567). The caller invokes a non-nil completion once, off the loop. A nil result means there is nothing to cycle to. The notifications end when ctx or the Session ends, as Session.SetModelOnMain's do.
func (*Session) BeginPreparedPrompt ¶
func (s *Session) BeginPreparedPrompt(ctx context.Context, start *RunStart, p *PreparedPrompt) (*PreparedPromptRun, error)
BeginPreparedPrompt claims the agent for the prompt that start prepared, after its held messages were flushed (agent-session.ts:1857 agent.prompt). An error abandons start. A busy agent rejects the run after acceptance; it is not serialized behind the old run.
func (*Session) BeginPromptCompactionCheck ¶
func (s *Session) BeginPromptCompactionCheck(ctx context.Context) (due func(context.Context) error, ok bool, err error)
BeginPromptCompactionCheck runs the policy half of prompt()'s compaction check on the calling goroutine and returns the compaction it decided on, or nil when none is due. A mode runs the returned function off its input loop, as Pi's check resumes without I/O unless it compacts. The Session lock is never waited for: ok is false when another operation holds it (a compaction in progress), and the caller then runs CheckPromptCompaction off its loop, so the loop keeps answering while Pi's own check would still be waiting for that compaction.
func (*Session) BeginRunStart ¶
BeginRunStart marks the Session busy for a user prompt's run (_startRun: `_isAgentRunActive = true; _agentRunAbortRequested = false`). A Session that is already busy rejects the prompt, as prompt() does when it is streaming (agent-session.ts:2098-2103).
func (*Session) BindExtensions ¶
func (s *Session) BindExtensions(ctx context.Context, bindings ExtensionBindings) error
BindExtensions stores the mode bindings the argument defines, always applies the stored bindings to the runner, awaits the configured session_start event and admits tools registered by its handlers before returning (upstream bindExtensions, agent-session.ts:3258-3282). Attach an event consumer before binding when handlers can send messages.
func (*Session) CacheWarmingStatus ¶
func (s *Session) CacheWarmingStatus() *icodingagent.CacheWarmingStatus
CacheWarmingStatus reports the current cache-warming state and the policy inputs that produced it, or nil when the Session has no warmer. Mirrors upstream AgentSession.cacheWarmingStatus.
func (*Session) CallableToolNames ¶
CallableToolNames returns the names of the tools that tools can call through `ctx.executeTool()`: the active `direct` tools and every registered `codemode` or `deferred` tool, in registry order.
upstream: agent-session.ts:1445-1448 (getCallableToolNames)
func (*Session) CheckModelAuth ¶
CheckModelAuth reports the error SetModel returns when m's provider has no configured auth (agent-session.ts:2477-2480 setModel's checkAuth step).
func (*Session) CheckPromptCompaction ¶
CheckPromptCompaction runs prompt()'s compaction check before a new user message, for a mode that starts the run itself with RunAgentPrompt.
func (*Session) ClearQueue ¶
ClearQueue removes and returns all queued user-message text. Queued extension custom messages stay queued and run with the active run. pig divergence (D135): upstream clearQueue also destroys custom messages queued by sendMessage(deliverAs) without returning them (Pi #9886).
func (*Session) Clone ¶
Clone snapshots the current path-to-leaf as a new session JSONL on disk, dropping orphan branches and recording the source as parentSession. File-backed Sessions must already be saved. The original Session is unchanged; the caller owns closing the returned Session.
func (*Session) CloneInPlace ¶
CloneInPlace duplicates the active branch and switches to the clone.
func (*Session) Close ¶
Close invalidates the extension runner this Session owns and releases the Session's resources without deleting its persisted JSONL. A runner borrowed from its Runtime or Clone source stays active; Runtime.Close invalidates the Runtime runner. Further Send calls fail; repeated Close calls are safe.
func (*Session) Compact ¶
func (s *Session) Compact(ctx context.Context, customInstructions string) (*CompactionResult, error)
Compact runs manual compaction and returns the generated result. Like upstream compact(), a session with nothing to compact is an error ("Nothing to compact (session too small)" or "Already compacted"); the compaction_end event reports it first.
func (*Session) CompactForExtension ¶
func (s *Session) CompactForExtension(ctx context.Context, customInstructions string) (extension.CompactionResult, error)
CompactForExtension runs an extension's ctx.compact({ onComplete, onError }) and returns the CompactionResult it reports (compaction.ts:105). Like Compact, a session with nothing to compact is an error: upstream's compact() rejects, and ctx.compact reports that through onError.
func (*Session) ContextUsage ¶
func (s *Session) ContextUsage() *SessionContextUsage
ContextUsage returns the projected context estimate (agent-session.ts getContextUsage). Token and percentage values are null after compaction until an assistant response after the latest compaction reports valid usage and still contributes to the projection.
The estimate depends only on the context window and the current branch, so it is reused until the Session log or the window changes: the state a subprocess extension receives before each event carries it, and a projection per streamed delta made every event cost O(history).
func (*Session) CreateReplacedSessionContext ¶
func (s *Session) CreateReplacedSessionContext(ctx context.Context) *extension.ReplacedSessionContext
CreateReplacedSessionContext captures the current bound command context and the Session's direct awaited message methods. Runtime calls it only after host rebinding finishes.
func (*Session) CycleModel ¶
func (s *Session) CycleModel(direction string, options ...ModelMutationOptions) (*ModelCycleResult, error)
CycleModel selects the next available model. Empty direction means forward; only Persist changes global defaults.
func (*Session) CycleThinkingLevel ¶
func (s *Session) CycleThinkingLevel(options ...ModelMutationOptions) (ai.ModelThinkingLevel, error)
CycleThinkingLevel advances through supported levels, returning an empty level for a non-reasoning model.
func (*Session) DeferCustomMessage ¶
func (s *Session) DeferCustomMessage(message agent.AgentMessage) bool
DeferCustomMessage holds a custom message an extension sent with triggerTurn false while a run streams, until that turn's tool results are complete (agent-session.ts:2351-2356). It reports false when no run is active, so the caller appends the message at once.
func (*Session) DiscardAddedDefaultTools ¶
func (s *Session) DiscardAddedDefaultTools()
DiscardAddedDefaultTools drops the tools ReloadSettings staged for the next RefreshTools. A reload that stops before it rebuilds the runtime calls it, because upstream's list is local to one reload() call and a later registry refresh must not activate it (agent-session.ts:3592-3609).
func (*Session) DiscardEvents ¶
func (s *Session) DiscardEvents()
DiscardEvents declares that nothing reads Events: Subscribe listeners are the only sinks, as in print mode. The Session then sends nothing on Events, so a publication never waits for or wakes a consumer, and FlushEvents returns once every preceding event has executed, without a consumer acknowledgement. Call it before the first run; markers already buffered on Events are acknowledged.
With or without it, a producer whose event has nothing queued ahead executes that event on its own goroutine, listeners included, as Pi's synchronous _emit does; the executor goroutine runs only events queued behind others.
func (*Session) DispatchSlash ¶
DispatchSlash runs a slash-command line through the session's registry and returns each line of output the handler emitted, plus any error.
Unlike the TUI dispatch path, DispatchSlash does NOT render to a chat scrollback; every Append call is captured into the returned []string. Slash commands that depend on TUI overlays (the interactive picker variants of /resume, /fork, /tree) automatically fall back to their text path because no PickSession / PickUserMessage / PickTreeEntry callbacks are wired in headless mode.
The same registry that powers the interactive TUI is used here, so whatever extension-registered slash commands the session knows about are reachable from SDK consumers too (provided their handlers are headless-safe).
Behavioural notes:
- /quit, /clear are no-ops in headless mode (they emit a single line acknowledging the call) since the SDK consumer controls the scrollback, not the session.
- /reset clears the agent's in-memory messages (does NOT delete the on-disk JSONL).
- Unknown commands return an error rather than silently no-op.
func (*Session) Dispose ¶
func (s *Session) Dispose()
Dispose stops the Session as upstream AgentSession.dispose does (agent-session.ts:1170-1185): it aborts retry, compaction, branch summary and bash, aborts the Agent, invalidates the extension runner, and disconnects the Session from the Agent. Later message, tool, turn and agent_end events then reach neither extensions nor persistence nor Session subscribers. Hooks installed on the Agent still run, so the aborted run's turn_end boundaries and agent_settled still reach extensions through the invalidated runner, whose ctx getters report it stale.
With its listeners gone the Session event executor ends: Events closes, and publishing or flushing an event no longer waits. The Session stops observing the model registry, so services that outlive it do not keep it reachable. The aborted run still settles; Close joins it.
Upstream runs these steps synchronously, so the aborted run cannot observe a partial dispose. The Agent runs on its own goroutine here, so the Session disconnects and invalidates before it aborts the Agent.
func (*Session) EmitSessionShutdown ¶
EmitSessionShutdown dispatches a session_shutdown event to extension handlers. reason is one of "quit" | "reload" | "new" | "resume" | "fork".
Mirrors upstream teardownCurrent (agent-session-runtime.ts:167), which emits session_shutdown on dispose in all modes. Paired with EmitSessionStart so the one-shot modes drive the full extension lifecycle rather than leaving start-without-shutdown extensions to leak.
func (*Session) EmitSessionShutdownTransition ¶
EmitSessionShutdownTransition dispatches session_shutdown with the target Session file when a runtime host changes Sessions.
func (*Session) EmitSessionStart ¶
EmitSessionStart dispatches a session_start event to extension handlers. reason is one of "startup" | "reload" | "new" | "resume" | "fork". Interactive replacements dispatch through the awaited mode rebind; headless startup callers use this helper.
func (*Session) EmitSessionStartTransition ¶
EmitSessionStartTransition dispatches session_start with the replaced Session's previous file when a runtime host changes Sessions, then extends the Session's resource loader with what resources_discover returns. A discovery error returns to the caller, as bindExtensions rejects with it (agent-session.ts:3207).
func (*Session) Entries ¶
func (s *Session) Entries() []icodingagent.SessionEntry
Entries returns all session entries in append order. The returned slice is a defensive copy; mutating it does not affect the session.
func (*Session) Events ¶
func (s *Session) Events() <-chan agent.AgentEvent
Events returns the channel of streaming agent events (text deltas, tool calls, tool results, etc.) emitted during Send. Buffered; consumers that fall behind will see send blocking inside the agent loop until they catch up. Unbuffered consumers should drain in a dedicated goroutine.
The channel is closed when the Session is Closed. A caller with no Events consumer calls DiscardEvents instead of draining it.
func (*Session) ExecuteBash ¶
func (s *Session) ExecuteBash(ctx context.Context, command string, onChunk func(string), options *ExecuteBashOptions) (BashResult, error)
ExecuteBash runs command in a shell outside the LLM agent loop and records the result so the agent sees it on the next turn. Mirrors upstream executeBash(command, onChunk, options) and recordBashResult (agent-session.ts). Each output chunk goes to onChunk, when set, and then to Session listeners before ExecuteBash returns.
Recording is deferred while an agent turn is streaming so it can't orphan a tool_use/tool_result pair; the buffered records are flushed at the end of the turn (see flushPendingBashLocked).
A notification's admission is released after Bash setup, before awaiting execution and output.
func (*Session) ExportToHTML ¶
func (s *Session) ExportToHTML(outputPath string, options ...ExportToHTMLOptions) (string, error)
ExportToHTML writes the Session as an HTML file and returns its path (agent-session.ts exportToHtml). The export embeds the live system prompt and active tool schemas, and draws a tool through its extension's renderers. It reports an in-memory Session or one without a file yet with upstream's messages.
func (*Session) ExportToJsonl ¶
ExportToJsonl writes the current branch (the session header, then every entry on the branch path) to outputPath and returns the path written; an empty path becomes a timestamped file in the working directory (agent-session.ts exportToJsonl).
func (*Session) ExtensionCommandActions ¶
func (s *Session) ExtensionCommandActions() extension.CommandActions
ExtensionCommandActions returns the command-context actions the Session backs in every mode. Modes may bind their own versions over them (for example to refresh a UI after navigating).
func (*Session) ExtensionCompact ¶
func (s *Session) ExtensionCompact(options *extension.CompactOptions)
ExtensionCompact is the compact action Pi binds for extensions in every mode. It starts a manual compaction without waiting for it and reports its result to options.OnComplete or its failure to options.OnError; without callbacks the outcome is dropped, as upstream's optional calls drop it. The compaction runs as a Session task: Close cancels and joins it, and a closed Session reports the rejection to options.OnError.
upstream: agent-session.ts:3369-3379 (_bindExtensionCore compact)
func (*Session) ExtensionHost ¶
func (s *Session) ExtensionHost() ExtensionHost
ExtensionHost returns the extension host of the Runtime that created the Session, or nil when that Runtime has none.
func (*Session) ExtensionRunner ¶
ExtensionRunner returns the Session's current extension runner, which reload and replacement change.
func (*Session) ExtensionSetModel ¶
ExtensionSetModel is the setModel action Pi binds for extensions in every mode. A provider without configured credentials answers false and changes nothing; otherwise the Session switches to model as SetModel does and answers true.
upstream: agent-session.ts:3343-3347 (_bindExtensionCore setModel)
func (*Session) ExtensionUserMessageRunPending ¶
ExtensionUserMessageRunPending reports whether a run an extension's sendUserMessage requested has not emitted agent_start yet. Pi's sendUserMessage goes through prompt(), which awaits the input handlers, the compaction check and before_agent_start before _startRun marks the Session busy, so the Session is still idle to the extension that sent it (agent-session.ts:2064-2140); here the run is prepared ahead of the extension's continuation and counts busy from its start (RunStart).
func (*Session) FlushDeferredCustomMessages ¶
FlushDeferredCustomMessages appends the custom messages held for the end of a turn.
func (*Session) FlushEvents ¶
FlushEvents waits until an opted-in Events consumer acknowledges all preceding events. The consumer calls AcknowledgeEvent before event conversion; it must not call FlushEvents from its own event callback. Cancellation and Close release the wait even when no consumer is running. After Dispose the Session has no listeners, so there is nothing to wait for. After DiscardEvents the barrier holds once every preceding event executed.
func (*Session) FollowUp ¶
func (s *Session) FollowUp(ctx context.Context, text string, images []ai.ImageContent, options *QueueInputOptions) (QueuedInputDisposition, error)
FollowUp awaits input handlers and skill/template expansion, rejects extension commands, and queues the result after the current turn's tools and steering finish.
func (*Session) FollowUpMode ¶
FollowUpMode reports how the Agent drains queued follow-up messages (agent-session.ts get followUpMode).
func (*Session) Fork ¶
Fork moves the session leaf to entryID. The next Send creates a new branch off that point. The agent's in-memory message history is rebuilt from the new path-to-leaf so the LLM sees only the new branch on the next turn.
Returns an error if entryID is unknown.
func (*Session) ForkToNewSession ¶
ForkToNewSession forks the given user message into a NEW session file (branched at the message's parent) and switches this session to it, rebuilding agent history from the new file. Mirrors upstream /fork (agent-session-runtime.ts fork(), position "before"). The selected message text is discarded here (headless has no editor to prefill); interactive callers use SessionManager.ForkToNewSession directly.
func (*Session) ForkToNewSessionWithText ¶
ForkToNewSessionWithText forks before a user message, switches this Session to the new file, and returns the selected message text.
func (*Session) GetAllTools ¶
GetAllTools returns every admitted definition, including inactive builtins, with its registration metadata.
func (*Session) GetFollowUpMessages ¶
GetFollowUpMessages returns queued follow-up text in admission order.
func (*Session) GetSessionStats ¶
func (s *Session) GetSessionStats() SessionStats
GetSessionStats returns aggregate stats for this session. Mirrors upstream getSessionStats (agent-session.ts:2887-2935).
func (*Session) GetSteeringMessages ¶
GetSteeringMessages returns queued steering text in admission order.
func (*Session) GetSystemPromptOptions ¶
func (s *Session) GetSystemPromptOptions() *extension.BuildSystemPromptOptions
GetSystemPromptOptions returns the live base prompt inputs used by command contexts. Mutations apply to this options object, not the Agent's active tool registry. Rebuilding the tool prompt replaces the object; previously borrowed options remain unchanged.
func (*Session) GetToolDefinition ¶
func (s *Session) GetToolDefinition(name string) (extension.ToolDefinition, bool)
GetToolDefinition returns the admitted definition for name.
func (*Session) HasDeferredCustomMessages ¶
HasDeferredCustomMessages reports whether a custom message waits for the end of its turn.
func (*Session) HasExtensionHandlers ¶
HasExtensionHandlers reports whether a loaded extension handles eventType (agent-session.ts hasExtensionHandlers). A Session without a runner has none.
func (*Session) HasPendingBashMessages ¶
HasPendingBashMessages reports whether bash results wait to be flushed after the agent turn (agent-session.ts get hasPendingBashMessages).
func (*Session) HasPendingMessages ¶
HasPendingMessages reports whether steering or follow-up messages are queued (upstream hasPendingMessages: pendingMessageCount > 0).
func (*Session) HiddenDeclarationNames ¶
HiddenDeclarationNames lists the tools whose declarations the loadout hides, in the order the hooks hid them: upstream's `hiddenTools: [...this._hiddenDeclarations]` (agent-session.ts _rebuildSystemPrompt).
func (*Session) HiddenDeclarations ¶
HiddenDeclarations returns the tools whose declarations the loadout hides from every request. A prompt built outside the Session lists no hidden tool.
func (*Session) HoldAgentEvents ¶
func (s *Session) HoldAgentEvents() (release func())
HoldAgentEvents stops the Agent at its next event, before the Session or any later listener sees it, until release is called. release may be called more than once.
It models Pi's single event loop during a termination signal's disposal (print-mode.ts:50-63): while the session_shutdown handlers run synchronously, a killed tool's exit, a provider response and every other source of Agent progress wait for the loop to turn. A mode holds the Agent before it kills tracked children, and releases it when a handler yields (see handleryield) or when the disposal ends. Pi's run goes on only from such a turn.
func (*Session) ID ¶
ID returns the session identifier (the part after the timestamp in the JSONL filename).
func (*Session) ImportFromJsonl ¶
func (s *Session) ImportFromJsonl(ctx context.Context, inputPath, cwdOverride string) (extension.CancelledResult, error)
ImportFromJsonl copies the session file at inputPath into the session directory and switches to the copy, as upstream importFromJsonl (agent-session-runtime.ts:361-404) does. inputPath resolves against the process working directory. A stored session is never replaced: a source that already lives in the session directory is opened in place, and any other source keeps its base name with the first free -N suffix and is copied exclusively. session_before_switch can cancel before anything is copied. cwdOverride replaces a stored working directory that no longer exists; without it such a session fails with MissingSessionCwdError after the copy.
func (*Session) Inner ¶
func (s *Session) Inner() *icodingagent.Session
Inner returns the underlying internal session handle.
PROVISIONAL: this method exists during the F3–F5 refactor so the pig binary's TUI layer (internal/codingagent.InteractiveMode) can share the same on-disk session a coding.Session owns. The return type is internal/codingagent.Session, which third-party consumers cannot import, so this method is effectively pig-internal even though it is exported. Likely to be removed once F4–F5 finalise the public API surface; SDK consumers should use the public Session methods (Path, ID, CWD, Messages, Send, etc.) instead.
func (*Session) IsBashRunning ¶
IsBashRunning reports whether a bash command is running (agent-session.ts get isBashRunning).
func (*Session) IsCompacting ¶
IsCompacting reports whether compaction or tree navigation is currently in flight.
func (*Session) IsIdle ¶
IsIdle reports whether the session has no active run and no compaction in flight (upstream isIdle).
func (*Session) IsRetrying ¶
IsRetrying reports whether an automatic retry wait is in progress (agent-session.ts get isRetrying: the retry abort controller exists).
func (*Session) IsStreaming ¶
IsStreaming reports whether an agent run, including its retries, compaction, and queued continuations, is active (upstream isStreaming).
func (*Session) LastAssistantText ¶
LastAssistantText returns the trimmed text of the most recent assistant message, or nil when there is none or its text is empty. An aborted message without content is skipped; the text joins every text block, and trimming follows JavaScript's String.prototype.trim. Ports packages/coding-agent/src/core/agent-session.ts getLastAssistantText.
func (*Session) LeafID ¶
LeafID returns the current leaf entry id, or nil if the session is empty (no entries yet).
func (*Session) ListSessions ¶
func (s *Session) ListSessions() ([]SessionInfo, error)
ListSessions returns the SessionInfo summaries for every JSONL in this session's working directory. Newest mtime first; corrupted files silently skipped.
func (*Session) Messages ¶
func (s *Session) Messages() []agent.AgentMessage
Messages returns a snapshot of the agent's in-memory message history. The slice is a defensive copy; callers may mutate it without affecting future Send calls.
func (*Session) ModelRegistry ¶
func (s *Session) ModelRegistry() *ModelRegistry
ModelRegistry returns the facade bound to the same ModelRuntime.
func (*Session) ModelRuntime ¶
func (s *Session) ModelRuntime() *ModelRuntime
ModelRuntime returns this Session's mode-independent model execution path.
func (*Session) NavigateTree ¶
func (s *Session) NavigateTree(ctx context.Context, targetID string, opts NavigateTreeOptions) (NavigateTreeResult, error)
NavigateTree forks the session to targetID, optionally generating a branch summary. This is the public SDK entry point (takes NavigateTreeOptions struct). The InteractiveSessionHandle bridge is NavigateTreeHandle below.
Mirrors upstream AgentSession.navigateTree() (agent-session.ts).
func (*Session) NavigateTreeHandle ¶
func (s *Session) NavigateTreeHandle(ctx context.Context, targetID string, options icodingagent.NavigateTreeOptions) (icodingagent.NavigateTreeResult, error)
NavigateTreeHandle implements the icodingagent.InteractiveSessionHandle interface: it forwards all four navigateTree options and returns icodingagent.NavigateTreeResult (structurally identical to coding.NavigateTreeResult).
func (*Session) NewSession ¶
NewSession replaces the active Session with a fresh Session.
func (*Session) ObserveReplicatedState ¶
func (s *Session) ObserveReplicatedState(observe func()) func()
ObserveReplicatedState registers observe to run after a change to Session state that an extension runtime replicates and that no extension call announced: the active model (set, cycled, restored with a replaced Session, or refreshed from the registry), the thinking level, the session name (set, or replaced with the Session) and the settings. Pi's extension context reads each of them live, so `ctx.model`, `pi.getThinkingLevel()`, `pi.getSessionName()` and `pi.getSettings()` return the new value at the next read (runner.ts:906, loader.ts:411-414, agent-session.ts); a runtime replicates the state, so its owner reports the change through this. observe runs on the goroutine that made the change, which may be the owner loop or hold a Session or settings lock: it must return at once and must not call back into the Session or its settings. It runs after the change, so a read from another goroutine sees the new state. The returned function removes the observer and can be called repeatedly.
func (*Session) OnAgentSettled ¶
func (s *Session) OnAgentSettled()
OnAgentSettled tells the cache warmer that an agent run settled, the first step of upstream AgentSession._emitAgentSettled.
func (*Session) PendingMessageCount ¶
PendingMessageCount returns the number of queued steering and follow-up messages.
func (*Session) PreparePrompt ¶
func (s *Session) PreparePrompt(ctx context.Context, content []ai.UserContentBlock) (*PreparedPrompt, error)
PreparePrompt awaits before_agent_start for the user prompt whose RunStart keeps the Session busy (agent-session.ts:1885-1936 _prepareRun). Hosts normalize images and admit the result after that await; a message or queued prompt sent while a handler is suspended joins the starting run.
func (*Session) Prompt ¶
Prompt awaits command/input dispatch, optional resource expansion, queueing or an ordinary turn. Extension command arguments retain all text after the first space. Invocation options do not replace system-prompt construction state.
func (*Session) PromptTemplates ¶
func (s *Session) PromptTemplates() []PromptTemplate
PromptTemplates returns the file-based prompt templates the Session's resource loader resolved (agent-session.ts promptTemplates).
func (*Session) QueueAgentStartMessages ¶
func (s *Session) QueueAgentStartMessages(messages []extension.CustomMessageRef)
QueueAgentStartMessages holds the messages a before_agent_start dispatch returned; the next prompt carries them as custom messages after the user message and any next-turn messages (agent-session.ts prompt()). Every mode that emits before_agent_start hands its result here.
func (*Session) QueueFollowUp ¶
func (s *Session) QueueFollowUp(text string, images []ai.ImageContent)
QueueFollowUp admits already-processed input after the active turn. Modes that own input dispatch use this boundary to avoid running handlers twice.
func (*Session) QueueSteer ¶
func (s *Session) QueueSteer(text string, images []ai.ImageContent)
QueueSteer admits already-processed input before the next model call. Modes that own input dispatch use this boundary to avoid running handlers twice.
func (*Session) ReapplyActiveTools ¶
ReapplyActiveTools applies the Session's own selection again after a mode replaced the agent's tool list, as interactive mode does when it rebuilds its tools on reload. Unlike SetActiveToolsByName it is not a new loadout, so the pending tools of a restored or reloaded loadout stay pending.
func (*Session) RecordBashResult ¶
func (s *Session) RecordBashResult(command string, result BashResult, excludeFromContext *bool) error
RecordBashResult records an extension-produced Bash result and returns immediate persistence failures. An active run defers persistence and owns any later flush error. Records retain their completion timestamp.
func (*Session) RecordUserBashResult ¶
func (s *Session) RecordUserBashResult(command string, result icodingagent.BashResult, excludeFromContext bool) error
RecordUserBashResult records an interactive user Bash result through recordBashResult (icodingagent.InteractiveSessionHandle).
func (*Session) RefreshContext ¶
func (s *Session) RefreshContext()
RefreshContext refreshes the agent's finalized transcript from the canonical Session projection (agent-session.ts refreshContext). Call it after appending entries to Inner() directly.
func (*Session) RefreshTools ¶
RefreshTools rebuilds registered definitions and their prompt contributions, preserves active selection, and activates newly admitted names.
func (*Session) RefreshToolsAfterReload ¶
RefreshToolsAfterReload is the tool registry rebuild of upstream's reload(): RefreshTools, except that without a tool allowlist every extension or SDK tool that activates on registration is active again, including one disabled during the session.
upstream: agent-session.ts:3604-3609 (_buildRuntime with includeAllExtensionTools), 3507-3510
Active tools that the reloaded extensions register later, such as MCP tools, are pending until then (upstream: agent-session.ts reload).
func (*Session) Reload ¶
func (s *Session) Reload(ctx context.Context, options ...ReloadOption) error
Reload is AgentSession.reload (agent-session.ts:3640-3685): the old extensions receive session_shutdown with reason reload and go stale; the settings and the resource loader are read again; the loader's extensions build a new runner that keeps the previous flag values; the tools a settings reload newly added to defaultTools activate; and, when the mode bound its UI or command actions, the new runner gets them and session_start with reason reload, then the resources its resources_discover handlers contribute. A failure before the new runner exists leaves the old one stale, as Pi does.
func (*Session) ReloadExtensions ¶
func (s *Session) ReloadExtensions(extensions []extension.Extension, runtime ...*extension.ExtensionRuntime) (*inproc.Runner, error)
ReloadExtensions is the runtime rebuild of upstream's reload() for the extensions the mode loaded again (agent-session.ts:3547-3567 _buildRuntime): a runner over them, bound to the Session, replaces the current one, which goes stale, and the tool registry is rebuilt so the tools a settings reload newly added to defaultTools activate and every extension tool that activates on registration is active again (agent-session.ts:3598-3609, RefreshToolsAfterReload). The caller binds its own UI and command actions to the returned runner and then emits session_start.
func (*Session) ReloadSettings ¶
func (s *Session) ReloadSettings()
ReloadSettings reloads the settings files. When the initial tools came from the `defaultTools` setting, the next RefreshTools activates the tools the reload newly added to it, replacing the list an earlier reload staged (each reload() call computes its own, agent-session.ts:3598-3601); removed tools stay active and tools disabled during the session stay disabled unless the setting newly adds them. upstream: agent-session.ts:3592-3609
func (*Session) ReplaceInner ¶
func (s *Session) ReplaceInner(sess *icodingagent.Session)
ReplaceInner aborts work owned by the old Session, then installs the new Session state, including whether its manager persists to a file.
func (*Session) ReplaceRunner ¶
ReplaceRunner atomically redirects lifecycle dispatch to the current extension generation after reload.
func (*Session) RequestAbort ¶
func (s *Session) RequestAbort()
RequestAbort stops Session continuations and cancels the Agent's signal without cancelling its caller context. An awaited before-settle hook still commits its drafts, but cannot continue. Extensions do not await the run they stop.
func (*Session) ResourceLoader ¶
func (s *Session) ResourceLoader() ResourceLoader
ResourceLoader returns the loader that supplies this Session's resources (agent-session.ts resourceLoader).
func (*Session) RetryAttempt ¶
RetryAttempt is the current automatic retry attempt, 0 when not retrying (agent-session.ts get retryAttempt).
func (*Session) RoutedModel ¶
func (s *Session) RoutedModel() *RoutedModel
RoutedModel returns, under a virtual selection, the physical model and thinking level of the latest successful response, or nil.
upstream: agent-session.ts:1408-1414 (routedModel)
func (*Session) RoutedModelSelection ¶
func (s *Session) RoutedModelSelection() *icodingagent.RoutedModelSelection
RoutedModelSelection is RoutedModel in the form the interactive footer renders.
func (*Session) RunAgentPrompt ¶
func (s *Session) RunAgentPrompt(ctx context.Context, start func(context.Context) ([]agent.AgentMessage, error)) ([]agent.AgentMessage, error)
RunAgentPrompt runs one agent run to settlement like Pi's _runAgentPrompt. start performs the low-level run that seeds it (a prompt, a custom message, or a continuation from queued input). Post-run handling then retries retryable errors, recovers from overflow and length stops, compacts over the threshold, and continues from input queued during the run, until nothing asks for another run or ctx is cancelled. It returns the last low-level run's messages and error, and does not emit agent_settled: the caller owns settlement.
The Session lock protects preparation and post-run handling, not the low-level run or its listeners. Before each continuation and before returning, this path waits until the Events consumer has handled every event emitted so far, as Pi's session listeners run before agent.continue() and before the run settles. The consumer must acknowledge FlushEvents barriers. Extension handlers already run synchronously on the agent goroutine. The run remains active for IsStreaming and Abort until RunAgentPrompt returns.
func (*Session) RunInputHandlers ¶
func (s *Session) RunInputHandlers(ctx context.Context, text string, images []ai.ImageContent, source extension.InputSource, behavior 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 (upstream _runInputHandlers). behavior ("steer" or "followUp") reaches the handlers only while a run is active, as upstream passes it only when streaming. A transform without images keeps the original images.
func (*Session) ScopedModels ¶
func (s *Session) ScopedModels() []ScopedModel
ScopedModels returns the current read-only cycling scope without copying its list or models. An empty scope means all available models.
func (*Session) Send ¶
Send appends a text prompt to the session, runs the agent loop until the LLM stops calling tools or until ctx cancels, and returns the full message slice produced this turn.
func (*Session) SendContent ¶
func (s *Session) SendContent(ctx context.Context, content []ai.UserContentBlock) ([]agent.AgentMessage, error)
SendContent dispatches extension commands before ordinary structured-content turns. Modes that already process commands and input use SendContentWithPreflight instead.
func (*Session) SendContentWithPreflight ¶
func (s *Session) SendContentWithPreflight(ctx context.Context, content []ai.UserContentBlock, preflight func()) ([]agent.AgentMessage, error)
SendContentWithPreflight starts a user prompt's run as agent-session.ts _startRun does (:1832-1877). Its input has already passed command/input dispatch. The Session is busy from the call on, so a message sent while preparation is suspended joins the run; preflight runs once the messages held meanwhile are appended, before the first request. The run owns cancellation and completes through agent_settled.
func (*Session) SendCustomMessage ¶
func (s *Session) SendCustomMessage(ctx context.Context, message extension.CustomMessageRef, options *extension.SendMessageOptions) error
SendCustomMessage awaits custom-message delivery and any triggered turn. An explicit false TriggerTurn defers an active turn's append until its tool results are complete.
func (*Session) SendExtensionUserMessage ¶
func (s *Session) SendExtensionUserMessage(content any, options *extension.SendUserMessageOptions) error
SendExtensionUserMessage is the bound extension action. The Session owns its continuation and reports failures without making the extension await the model turn.
func (*Session) SendExtensionUserMessageStaged ¶
func (s *Session) SendExtensionUserMessageStaged(content any, options *extension.SendUserMessageOptions, stage *ExtensionRunStage) error
SendExtensionUserMessageStaged is SendExtensionUserMessage whose run preparation and start stage places; a nil stage runs both on the caller.
func (*Session) SendMessage ¶
func (s *Session) SendMessage(message extension.CustomMessageRef, options *extension.SendMessageOptions) error
SendMessage is the bound extension action. The Session owns triggered work and reports failures through its extension error listeners.
func (*Session) SendMessageStaged ¶
func (s *Session) SendMessageStaged(message extension.CustomMessageRef, options *extension.SendMessageOptions, stage *ExtensionRunStage) error
SendMessageStaged is SendMessage whose idle triggerTurn run preparation and start stage places; a nil stage starts the run as SendMessage does.
func (*Session) SendUserMessage ¶
func (s *Session) SendUserMessage(ctx context.Context, content any, options *extension.SendUserMessageOptions) error
SendUserMessage awaits the Session's extension-originated user turn or queue operation. Expansion defaults to false.
func (*Session) Services ¶
func (s *Session) Services() *AgentSessionServices
Services returns the parent Services container.
func (*Session) SessionManager ¶
func (s *Session) SessionManager() *SessionManager
SessionManager returns the backing log. A supplied manager is used directly; appends through either handle are visible through the other.
func (*Session) SessionName ¶
SessionName returns the current user-defined session name (set via /name or SetSessionName), or "" if none has been set. Mirrors upstream session.sessionName getter (agent-session.ts:849).
func (*Session) SetActiveToolsByName ¶
SetActiveToolsByName activates registered tools in the requested order and ignores unknown and hidden names. The next provider request declares the loadout and rebuilt structured tool prompt. Opaque caller prompts and forced run prompts remain unchanged. Mirrors upstream AgentSession.setActiveToolsByName.
func (*Session) SetAutoCompactionEnabled ¶
SetAutoCompactionEnabled persists the global compaction setting (agent-session.ts setAutoCompactionEnabled). Like Pi's settings setters it does not fail: a write failure is recorded by the settings manager for the settings diagnostics.
func (*Session) SetAutoRetryEnabled ¶
SetAutoRetryEnabled toggles the auto-retry setting (agent-session.ts setAutoRetryEnabled). Like Pi's settings setters it does not fail: a write failure is recorded by the settings manager for the settings diagnostics.
func (*Session) SetBeforeSessionReplacement ¶
SetBeforeSessionReplacement installs the mode's awaited drain after cancellable before hooks approve replacement and before shutdown is emitted.
func (*Session) SetCacheWarmingMode ¶
func (s *Session) SetCacheWarmingMode(mode icodingagent.CacheWarmingMode) error
SetCacheWarmingMode persists the cache-warming mode and immediately reconciles active warming. Mirrors upstream AgentSession.setCacheWarmingMode.
func (*Session) SetFollowUpMode ¶
SetFollowUpMode updates the active queue and persists its drain mode.
func (*Session) SetModel ¶
func (s *Session) SetModel(m *ai.Model, options ...ModelMutationOptions) error
SetModel swaps the active LLM model and records a model_change in the Session transcript. The next Send uses the new provider/model; tools, system prompt, and history are unchanged. Global model defaults change only with Persist. The thinking default never changes here. Runtime-managed providers must have configured auth.
func (*Session) SetModelOnMain ¶
func (s *Session) SetModelOnMain(ctx context.Context, m *ai.Model, options ModelMutationOptions, dispatch func(func() error) error) error
SetModelOnMain checks auth on the caller, dispatches only the synchronous state mutation to the owner loop, and waits for notifications on the caller. A superseded dispatcher can reject the mutation without executing it. The auth check and the notifications end when ctx or the Session ends: an owner that stops cancels ctx rather than wait for a handler, as Pi's shutdown exits without awaiting model_select (interactive-mode.ts:4251-4291).
func (*Session) SetName ¶
SetName persists a session name as a SessionInfoEntry on disk. It rejects ECMAScript-trimmed empty names. The name surfaces in ListSessions / Runtime.ListSessions output and in the resume picker UI.
func (*Session) SetPromptResources ¶
func (s *Session) SetPromptResources(templates []PromptTemplate, skills []*Skill)
SetPromptResources replaces the skills and prompt templates this Session reads with the resource owner's current resolved collections, keeping the loader's context files and system prompt text. It does not discover resources or change their configuration, and it does not rebuild the system prompt.
func (*Session) SetRebindSession ¶
SetRebindSession installs the awaited mode rebind for Session-owned replacements. The callback renders and subscribes to the destination before dispatching its session_start event.
func (*Session) SetRetryContinuationScheduler ¶
func (s *Session) SetRetryContinuationScheduler(schedule func(func()))
SetRetryContinuationScheduler binds the host's Promise-reaction queue for retry prefix and completion steps. A host that supplies a queue must drain it while awaiting Session operations and keep consuming Events until Close finishes. Without a queue, the run's worker owns these steps.
func (*Session) SetRunPrompt ¶
func (s *Session) SetRunPrompt(run *icodingagent.BeforeAgentStartRun)
SetRunPrompt publishes the before_agent_start run of a prompt that interactive mode prepared itself, so the Session's request hooks record the run's prompt sections in the transcript as they do for a prompt the Session prepared (agent-session.ts:1724 builds the run's options for every mode). Nil ends the run. The Session refreshes the options before each later turn.
func (*Session) SetScopedModels ¶
func (s *Session) SetScopedModels(models []ScopedModel)
SetScopedModels replaces the session-only cycling scope, retaining the supplied list and model identities without changing settings. Nil means an empty scope.
func (*Session) SetSessionName ¶
SetSessionName persists the sanitized Session name, immediately notifies subscribers, and admits the extension handler's synchronous prefix before returning. Suspended extension work belongs to the Session lifetime. An empty name clears the current name; RPC and slash-command boundaries validate their own non-empty input.
func (*Session) SetSteeringMode ¶
SetSteeringMode updates the active queue and persists its drain mode.
func (*Session) SetSystemPromptResources ¶
func (s *Session) SetSystemPromptResources(resources SystemPromptResources)
SetSystemPromptResources replaces the resource-loader state behind the base prompt options, as a resource reload does in Pi.
func (*Session) SetSystemPromptSections ¶
func (s *Session) SetSystemPromptSections(sections ai.OrderedSections)
SetSystemPromptSections replaces the caller-built structured prompt and resolves its tool-owned sections against the active registry. The next request records the change in the transcript.
func (*Session) SetThinkingLevel ¶
func (s *Session) SetThinkingLevel(level ai.ModelThinkingLevel, options ...ModelMutationOptions) error
SetThinkingLevel records a changed, clamped level in the Session transcript. With Persist, it saves the requested level as the global default even when the effective level is unchanged. A change admits the thinking_level_select handlers' synchronous prefix before returning; Pi does not await them (agent-session.ts:2629). Suspended handler work belongs to the Session lifetime.
func (*Session) SetThinkingLevelOnMain ¶
func (s *Session) SetThinkingLevelOnMain(level ai.ModelThinkingLevel, options ModelMutationOptions, dispatch func(func() error) error) error
SetThinkingLevelOnMain dispatches only the synchronous state mutation to the owner loop and runs the thinking_level_select notification on the caller, as SetModelOnMain does: the notification admits an extension handler's synchronous prefix, which must not run on the input loop. A superseded dispatcher can reject the mutation without executing it.
func (*Session) SettingsManager ¶
func (s *Session) SettingsManager() *icodingagent.SettingsManager
SettingsManager is upstream AgentSession.settingsManager (agent-session.ts:371): the settings this Session reads its compaction, retry, image and cache-warming policy from.
func (*Session) Signal ¶
Signal returns the active run's cancellation, or nil when no run is active. Extensions read it as ctx.signal.
upstream: agent-session.ts:3368 (`getSignal: () => this.agent.signal`)
func (*Session) SlashCommands ¶
func (s *Session) SlashCommands() []extension.SlashCommandInfo
SlashCommands lists the commands pi.getCommands() reports: the extension commands under their invocation names, then the prompt templates, then the skills (named `skill:<name>`) of the Session's resource loader, each with the sourceInfo the resource carries; a resource without one gets the provenance its path has under the Session's project and user directories (agent-session.ts _bindExtensionCore getCommands).
func (*Session) SlashCommandsFor ¶
func (s *Session) SlashCommandsFor(runner *inproc.Runner) []extension.SlashCommandInfo
SlashCommandsFor is the getCommands action agent-session.ts _bindExtensionCore (:3361-3384) binds to the runner it is given. The Session's own binding and every mode's extension binding use it, so an extension reads the list SlashCommands reports; a runtime replacement binds its new runner before the Session's current one changes.
func (*Session) StartEvent ¶
func (s *Session) StartEvent() extension.SessionStartEvent
StartEvent returns the session_start event this Session's extensions receive when a mode binds them: startup for the first Session, or the replacement reason and previous file.
func (*Session) State ¶
func (s *Session) State() agent.AgentState
State is the agent's live state (agent-session.ts:1426 `get state()` returns this.agent.state).
func (*Session) Steer ¶
func (s *Session) Steer(ctx context.Context, text string, images []ai.ImageContent, options *QueueInputOptions) (QueuedInputDisposition, error)
Steer awaits input handlers and skill/template expansion, rejects extension commands, and queues the result before the next model call.
func (*Session) SteeringMode ¶
SteeringMode reports how the Agent drains queued steering messages (agent-session.ts get steeringMode).
func (*Session) StreamModel ¶
func (s *Session) StreamModel(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
StreamModel starts a mode-independent model operation through this Session's runtime.
func (*Session) Subscribe ¶
func (s *Session) Subscribe(listener AgentSessionEventListener) func()
Subscribe registers a synchronous Session event listener and returns its unsubscribe function. Listeners run in registration order before the corresponding event is exposed on Events. Queue mutations notify on the caller's stack and may recursively change queues; event publication remains owned by the Session executor.
func (*Session) SummarizeForBugReport ¶
SummarizeForBugReport asks the session model for a bug report summary of the current conversation. /bug calls it only after the user chose a summary instead of attaching the transcript. Mirrors upstream AgentSession.summarizeForBugReport.
The request takes the summarization auth and routing of compaction: a virtual model is routed first and its thinking level applies (agent-session.ts:4307-4321). Its retries emit no summarization retry events, because Pi passes no retry callbacks.
func (*Session) SupportsThinking ¶
SupportsThinking reports whether the current model reasons (agent-session.ts supportsThinking: `!!this.model?.reasoning`). A model also reasons when its capabilities name a maximum thinking level.
func (*Session) SwitchSession ¶
SwitchSession loads a Session file and makes it active.
func (*Session) SystemPrompt ¶
SystemPrompt returns the effective run prompt while running and the base prompt between runs, independently of the retained active loadout.
func (*Session) ThinkingLevel ¶
func (s *Session) ThinkingLevel() ai.ModelThinkingLevel
ThinkingLevel returns the effective reasoning level used for future calls (agent-session.ts:1447 `this.agent.state.thinkingLevel`).
func (*Session) ToolActions ¶
func (s *Session) ToolActions() extension.ToolActions
ToolActions is the ExecuteTool, GetCallableTools and AppendEntry of the extension context actions. A host that runs extensions in another process binds them to its bridge, so a nested call from a subprocess extension reaches this session; a declarative tool reaches AppendEntry through its tool context.
upstream: agent-session.ts:3382-3383 (the executeTool and getCallableTools actions bound to the runner), 3339 (getSettings), 3321-3327 (appendEntry)
func (*Session) Tools ¶
Tools returns a defensive copy of the active loadout. Use GetAllTools for admitted definitions that are currently inactive.
func (*Session) Tree ¶
func (s *Session) Tree() *icodingagent.SessionTreeNode
Tree returns the session's branch tree as a SessionTreeNode. The returned structure is a defensive copy; mutating it does not affect the session's state. The node uses the internal codingagent tree type.
func (*Session) UserMessagesForForking ¶
func (s *Session) UserMessagesForForking() []ForkMessage
UserMessagesForForking returns all user messages with their session entry IDs, suitable for presenting fork targets to the user. Mirrors upstream getUserMessagesForForking (agent-session.ts:2856).
func (*Session) ValidateFork ¶
ValidateFork reports the error that forking at entryID would return from this Session without running any handler or replacing anything: an entry that does not exist or is not a user message for position "before", or a file-backed Session that has not been saved. A caller that dispatches a fork while another replacement is still in flight uses it to answer a request that Pi rejects before that replacement applies.
func (*Session) ValidatePromptModelAuth ¶
ValidatePromptModelAuth rejects a new prompt before compaction and before_agent_start when no model is selected or its provider has no usable auth, as agent-session.ts:1673-1691 does: the published availability snapshot first, then a live auth check. Interactive mode runs the same check before it starts a turn.
type SessionContextUsage ¶
type SessionEntry ¶
type SessionEntry = icodingagent.SessionEntry
SessionEntry is upstream SessionEntry: one entry of a session file, as FindCutPoint and GetLastAssistantUsage read it.
type SessionGraph ¶
type SessionGraph struct{}
SessionGraph is the host's SessionGraphBackend: it builds the objects extensions construct and answers their static functions.
func NewSessionGraph ¶
func NewSessionGraph() *SessionGraph
NewSessionGraph returns the backend to bind with Host.SetSessionGraph.
func (*SessionGraph) New ¶
func (*SessionGraph) New(ctx context.Context, scope subprocess.SessionGraphScope, kind, op string, args json.RawMessage) (subprocess.SessionGraphObject, error)
New implements subprocess.SessionGraphBackend.
func (*SessionGraph) Static ¶
func (*SessionGraph) Static(ctx context.Context, scope subprocess.SessionGraphScope, kind, method string, args json.RawMessage) (any, error)
Static implements subprocess.SessionGraphBackend.
type SessionImportFileNotFoundError ¶
type SessionImportFileNotFoundError = icodingagent.SessionImportFileNotFoundError
SessionImportFileNotFoundError identifies a missing import input before the active Session changes.
type SessionInfo ¶
type SessionInfo = icodingagent.SessionInfo
SessionInfo is the picker-display summary for a session JSONL. Re-exported alias from internal/codingagent.
type SessionManager ¶
type SessionManager = icodingagent.Session
SessionManager is the actual append-only Session log used by the runtime. Sharing this pointer shares entry identity, branching and persistence, not a copied projection.
func NewInMemorySessionManager ¶
func NewInMemorySessionManager(cwd string) (*SessionManager, error)
NewInMemorySessionManager creates a Session log with no persistence path. An empty cwd resolves to the process working directory.
func SessionManagerFor ¶
func SessionManagerFor(svcs *AgentSessionServices, opts SessionStartOptions) (*SessionManager, error)
SessionManagerFor returns the log a Session started with opts wraps, as NewSession selects it: the supplied manager, the opened resume path, or a new persisted or in-memory log. CreateAgentSessionRuntime needs the log before the factory runs.
type SessionOptions ¶
type SessionOptions struct {
// SessionManager supplies the actual backing log instead of creating or loading another one.
SessionManager *SessionManager
// Model is the selected LLM model. Nil allows an existing Session to restore its saved selection.
Model *ai.Model
// ThinkingLevel overrides restored and configured preferences before model clamping. Empty uses the Session or settings preference.
ThinkingLevel ai.ModelThinkingLevel
// ScopedModels selects the ordered models and optional thinking preferences for cycling.
ScopedModels []ScopedModel
// SystemPrompt supplies an explicit full-text baseline, retained as one preamble section.
// When omitted, the Session builds the default coding prompt.
SystemPrompt string
// SystemPromptSections supplies the ordered prompt state assembled by the caller.
// When non-nil it takes precedence over SystemPrompt and is diffed on each prompt.
SystemPromptSections ai.OrderedSections
// ResourceLoader supplies the skills, prompt templates, context files and system prompt text the Session expands, reports and builds its default system prompt from (Pi's createAgentSession resourceLoader). When nil, the Session uses a DefaultResourceLoader over the Services' cwd, agent directory and settings, which reloads the Services' settings, dropping their transient ApplyOverrides, and discovers resources at construction, as createAgentSession does. Supply NoResources to bind none and leave the system prompt to SystemPrompt, SystemPromptSections and SystemPromptResources.
ResourceLoader ResourceLoader
// SystemPromptResources is the resource-loader state (custom prompt, appended text, context files, skills) behind SystemPromptSections. It is what before_agent_start and getSystemPromptOptions report; nil reports SystemPrompt as the custom prompt.
SystemPromptResources *SystemPromptResources
// Agent is an Agent the caller built, which the Session drives instead of building its own (Pi's AgentSessionConfig.agent, agent-session.ts:253,486).
// The Session installs its hooks into it, chaining a FinishTurn, PrepareRequest, PrepareNextTurn and TransformLLMMessages hook the Agent already had, and sets its tools and session ID.
// It replaces the Agent's BeforeToolCall and AfterToolCall, as AgentSession assigns agent.beforeToolCall and agent.afterToolCall, and its PreparePrompt, PrepareToolResult and SessionFile, which only a Session sets.
// The caller owns the rest of the Agent's configuration, as sdk.ts createAgent does for Pi: stream function, TransformContext, OnPayload and header hooks (so no extension context, before_provider_request or before_provider_headers event fires unless the caller's hooks emit it), steering and follow-up modes, thinking budgets, transport and image conversion.
// A nil Model and ThinkingLevel take the Agent's, so the Session does not restore them from history. An Agent serves one Session; the Session's Clone and replacements build their own.
// Without it the Session builds its Agent with the cache-warming stream function.
// pig divergence (D113): Pi's AgentSessionConfig.extensionRunnerRef cell does not exist; a caller reads Session.ExtensionRunner() after construction.
Agent *agent.Agent
// CacheWarmer is a cache warmer the caller built, which the Session drives instead of building its own (Pi's AgentSessionConfig.cacheWarmer, agent-session.ts:266,494-497).
// The Session wires its OnWarmed to the entry_appended event, reports its Status, forwards OnAgentSettled and OnModeChanged, and cancels it when the Session closes.
// The caller's stream function starts it, as sdk.ts's does for Pi. A Session replacement builds its own warmer for the new Session.
CacheWarmer CacheWarmer
// Tools layered on top of the default coding-tool set
// (read/write/bash/edit/grep/find/ls). Caller-supplied tools
// take precedence on name collision.
Tools []agent.AgentTool
// CustomTools are SDK tool definitions with synthetic SDK source metadata.
CustomTools []extension.ToolDefinition
// NoTools disables all tools ("all") or only the initial builtin selection ("builtin").
NoTools string
// Services is the dependency container (settings, resources, model runtime, working directory) NewAgentSession builds the Session against;
// NewSession takes it as its first argument and ignores this field.
// upstream: agent-session.ts:485-494 (the constructor reads cwd, settingsManager, resourceLoader and modelRuntime from its config), sdk.ts CreateAgentSessionFromServicesOptions.services
Services *AgentSessionServices
// SkipBuiltinTools omits the built-in coding tools while still allowing
// caller-supplied and extension tools.
SkipBuiltinTools bool
// AllowedTools, if non-nil, is the allowlist filter applied at
// agent-loop time. nil = no restriction; non-nil empty = block
// every tool. Mirrors agent-frontmatter `tools:` field. Entries are tool
// names or patterns where `*` matches any characters (`--tools`). A
// non-empty list without `mcp__` entries keeps MCP tools registered for
// codemode and tool_search; only tool_search can declare them
// (sdk.ts tools, agent-session.ts allowedToolNames).
AllowedTools map[string]struct{}
// InitialActiveToolNames, when non-nil, are the tools active at start, in
// this order (agent-session.ts initialActiveToolNames). The active list
// keeps the caller's order; names the registry lacks or the tool filter
// rejects are dropped (agent-session.ts:3552-3554, _applyToolLoadout).
// With AllowedTools, the registered tools AllowedTools names or matches
// follow in registry order (agent-session.ts:3556-3562). The CLI passes
// its --tools list, or the defaultTools setting, minus --exclude-tools,
// as sdk.ts:274-276 does. A name that is not a built-in activates the
// registered extension or SDK tool of that name. nil uses the
// defaultTools setting or upstream's default [read, bash, edit, write].
// grep/find/ls remain registered but inactive unless named.
InitialActiveToolNames []string
// DefaultToolModifiers are the `+name`/`-name` entries of a `--tools` list that changed the default selection instead of replacing it. The Session keeps them: a settings reload applies them to the new defaultTools, so a tool removed with `-name` stays removed.
// upstream: sdk.ts:285,473 (defaultToolModifiers), agent-session.ts:3667-3670
DefaultToolModifiers []string
// BaseToolsOverride replaces the built-in coding tools as the session's base tool set, in order: each entry is one property of upstream's
// `Record<string, AgentTool>`, and the names are the tools active at start unless InitialActiveToolNames or a tool selection says otherwise.
// nil registers the built-in tools.
// upstream: agent-session.ts:294 (baseToolsOverride), 3614-3624, 3650-3652
BaseToolsOverride []BaseToolOverride
// UsesDefaultTools reports that the initial tools come from the defaultTools setting, so a settings reload activates the tools newly added to it. NewAgentSession treats nil as false, as the AgentSession constructor does; NewSession derives nil as createAgentSession does (no tool list, or one of only +name/-name entries, and no noTools), except that a BaseToolsOverride session does not use them.
// upstream: agent-session.ts:273,500 (usesDefaultTools), sdk.ts:472
UsesDefaultTools *bool
// ExcludedTools, when non-empty, is a denylist removed from the final
// tool set after allow/active filtering. It gates built-in AND
// extension/caller tools, so an excluded tool is non-callable, not just
// hidden from the prompt. Mirrors upstream excludedToolNames (sdk.ts:246)
// and isAllowedTool's `&& !excludedToolNames?.has(name)`
// (agent-session.ts:2288).
ExcludedTools map[string]struct{}
// BeforeToolCall hooks fire before any tool executes; can block
// or transform args. See agent.BeforeToolCallHook.
BeforeToolCall []agent.BeforeToolCallHook
// AfterToolCall hooks fire after each tool result. Each hook may
// return content/isError overrides and a terminate signal. Terminate
// stops the agent loop when every tool in the batch signals it
// (upstream shouldTerminateToolBatch semantics).
AfterToolCall []agent.AfterToolCallHook
// Runner is the extension runner for dispatching lifecycle events
// (before_agent_start, etc.). Nil creates an empty runner for the Session context.
Runner *inproc.Runner
// ResumePath, when non-empty, loads an existing session JSONL
// from disk and rebuilds the agent's message history from
// session.BuildContext(nil). Mutually exclusive with creating a
// fresh session.
ResumePath string
// CWDOverride selects an effective cwd for an opened Session without changing its stored header.
CWDOverride *string
// SessionDir overrides the on-disk session directory used for new
// sessions and resume-path lookups.
SessionDir string
// SessionID specifies an exact session ID for new sessions.
// Mirrors upstream --session-id (v0.76.0).
SessionID string
// NoSession disables session persistence while keeping the session id usable
// for provider cache affinity.
NoSession bool
// EventBufferSize controls the buffer for Session.Events(). Zero
// → 64 (a sensible default that won't block typical UI consumers
// while still bounding memory).
EventBufferSize int
// Transport requests a provider-specific streaming transport.
Transport ai.Transport
// contains filtered or unexported fields
}
SessionOptions configures NewSession.
type SessionStartOptions ¶
type SessionStartOptions struct {
// SessionManager selects the actual log to wrap, ahead of file loading or creation.
SessionManager *SessionManager
// ScopedModels supplies the read-only cycling scope, including optional per-model thinking levels.
ScopedModels []extension.ScopedModel
// Model is the LLM the agent calls. Required.
Model *ai.Model
// ThinkingLevel overrides restored and configured preferences before model clamping. Empty uses the Session or settings preference.
ThinkingLevel ai.ModelThinkingLevel
// SystemPrompt is the system prompt.
SystemPrompt string
// SystemPromptSections carries the caller-built structured prompt.
SystemPromptSections ai.OrderedSections
// SystemPromptResources is the resource-loader state behind SystemPromptSections.
SystemPromptResources *SystemPromptResources
// ResourceLoader supplies the Session's resources. See SessionOptions.ResourceLoader.
ResourceLoader ResourceLoader
// AllowedTools restricts which tools may execute.
AllowedTools map[string]struct{}
// InitialActiveToolNames are the tools active at start, in this order;
// see SessionOptions.InitialActiveToolNames (sdk.ts:274-276).
InitialActiveToolNames []string
// DefaultToolModifiers are the `+name`/`-name` entries of a tool list that changed the default selection; a settings reload applies them to the new defaultTools. See SessionOptions.DefaultToolModifiers.
DefaultToolModifiers []string
// ExcludedTools is a denylist of tool names removed from the final tool
// set after allow/active filtering. Gates built-in and extension/caller
// tools alike. Mirrors upstream excludedToolNames (sdk.ts:246).
ExcludedTools map[string]struct{}
// NoTools mirrors upstream SDK noTools behavior when no explicit allowlist
// is provided.
// - "all": expose no tools
// - "builtin": omit built-in coding tools but keep extension/extra tools
NoTools string
// SkipBuiltinTools, when true, omits the built-in coding tools while still
// allowing extension and extra tools.
SkipBuiltinTools bool
// BeforeToolCall hooks run before each tool call and may block.
BeforeToolCall []agent.BeforeToolCallHook
// ExtraTools are tools to add ON TOP of extension tools.
ExtraTools []agent.AgentTool
// SkipExtensionTools, when true, omits extension tools.
SkipExtensionTools bool
// ResumePath, when non-empty, loads an existing JSONL.
ResumePath string
// CWDOverride selects the effective cwd when opening a Session.
CWDOverride *string
// SessionDir overrides the on-disk session directory for new sessions
// and session lookups such as Resume/Continue.
SessionDir string
// SessionID specifies an exact session ID for new sessions.
// Mirrors upstream --session-id (v0.76.0).
SessionID string
// NoSession disables session persistence (ephemeral mode).
// Mirrors upstream --no-session (args.ts:92).
NoSession bool
}
SessionStartOptions configures a single Session within a Runtime.
type SessionStats ¶
type SessionStats struct {
SessionFile string `json:"sessionFile,omitempty"`
SessionID string `json:"sessionId"`
UserMessages int `json:"userMessages"`
AssistantMessages int `json:"assistantMessages"`
ToolCalls int `json:"toolCalls"`
ToolResults int `json:"toolResults"`
TotalMessages int `json:"totalMessages"`
Tokens SessionStatsTokens `json:"tokens"`
Cost float64 `json:"cost"`
ContextUsage *SessionContextUsage `json:"contextUsage,omitempty"`
}
SessionStats holds aggregate counters for a session. Mirrors upstream SessionStats interface (agent-session.ts:200-215).
type SessionStatsTokens ¶
type SessionStatsTokens struct {
Input int `json:"input"`
Output int `json:"output"`
CacheRead int `json:"cacheRead"`
CacheWrite int `json:"cacheWrite"`
Total int `json:"total"`
}
SessionStatsTokens holds per-category token counts.
type SessionTreeNode ¶
type SessionTreeNode = icodingagent.SessionTreeNode
SessionTreeNode is the branched tree of session entries. Re-exported alias from internal/codingagent.
type Settings ¶
type Settings = icodingagent.Settings
Settings is the merged user-settings view. Global settings are overlaid by project settings. The alias keeps the embedding API identical to the runtime representation.
type SettingsManager ¶
type SettingsManager = icodingagent.SettingsManager
SettingsManager is the live settings reader (re-exported alias). Use Services.Settings() to obtain the merged Settings; use Services.SettingsManager() if you need to call Reload() or watch for project-level changes.
func NewInMemorySettingsManager ¶
func NewInMemorySettingsManager(settings Settings) *SettingsManager
NewInMemorySettingsManager creates independent settings without file I/O. Pass it through CreateAgentSessionServicesOptions.SettingsManager to use it for Sessions. Ports packages/coding-agent/src/core/settings-manager.ts:403-410.
type Skill ¶
type Skill = icodingagent.SkillDef
Skill is a resolved skill supplied by the resource owner.
type SkillsResult ¶
type SkillsResult struct {
Skills []*Skill
Diagnostics []extension.ResourceDiagnostic
}
SkillsResult is a loader's skills with the diagnostics found while resolving them.
type SlashContextHandle ¶
type SlashContextHandle struct {
Args string
Append func(msg string)
AppendText func(msg string)
Clear func()
Quit func()
Reset func()
ModelName func() string
ToolNames func() []string
SkillNames func() []string
SessionInfo func() (string, string, int)
LastAssistant func() string
CopyClipboard func(string) error
CostSummary func() string
CurrentSession func() *icodingagent.Session
SetSessionName func(string) error
ForkAtEntry func(string) error
ForkToNewSession func(string) error
CloneCurrent func() (string, error)
ListSessions func() ([]SessionInfo, error)
RenderTree func() string
PickSession func() (string, bool)
PickUserMessage func() (string, bool)
PickTreeEntry func(initialSelectedID string) (string, bool)
LoadSessionPath func(string) error
}
SlashContextHandle is the SDK-facing form of the slash-context callbacks. SDK consumers don't construct these directly; they're produced inside DispatchSlash and forwarded to the internal registry.
PROVISIONAL: this type exists to bridge the internal SlashContext to the public API during F3-F5. May be replaced with a leaner public surface (e.g., a single `Output []string` callback) once F4-F5 narrow the SDK contract.
type SwitchSessionOptions ¶
type SwitchSessionOptions struct {
// CwdOverride replaces the Session's stored working directory when that directory no longer exists.
CwdOverride string
// WithSession runs against the replaced Session's context once the replacement settles.
WithSession func(*extension.ReplacedSessionContext) error
// ProjectTrustContextFactory returns the project trust context of the destination cwd; its UI serves the trust prompt.
ProjectTrustContextFactory func(cwd string) extension.ProjectTrustContext
}
SwitchSessionOptions is the options object of AgentSessionRuntime.switchSession (agent-session-runtime.ts:196-201).
type SystemPromptResources ¶
type SystemPromptResources struct {
CustomPrompt string
CustomPromptSet bool
AppendSystemPrompt string
ContextFiles []extension.SystemPromptContextFile
Skills []extension.SystemPromptSkill
}
SystemPromptResources is the resource-loader input of Pi's _rebuildSystemPrompt (agent-session.ts:1379-1391): the system prompt override, the joined append text, the loaded context files and the loaded skills.
type ThemesResult ¶
type ThemesResult struct {
Themes []*tui.Theme
Diagnostics []extension.ResourceDiagnostic
}
ThemesResult is a loader's themes with the diagnostics found while resolving them.
type TreePreparation ¶
type TreePreparation = extension.TreePreparation
TreePreparation is the session_before_tree preparation (extensions types.ts TreePreparation), received by extensions as SessionBeforeTreeEvent.Preparation.
type VirtualModelDefinition ¶
type VirtualModelDefinition = extension.VirtualModelDefinition
VirtualModelDefinition is a selectable catalog entry that routes each request to a physical model. upstream: virtual-models.ts:87-101
type VirtualModelStateData ¶
type VirtualModelStateData = extension.VirtualModelStateData
VirtualModelStateData is the data of a `pi.virtual-model-state` custom entry. upstream: virtual-models.ts:35-39
Source Files
¶
- auth_storage.go
- block_images.go
- bug_report.go
- client_identity.go
- compaction_api.go
- create_agent_session.go
- define_tool.go
- discover_extensions.go
- doc.go
- early_model_stream.go
- extension_bridge.go
- extension_flag_values.go
- extension_host.go
- extension_runner.go
- model.go
- model_api_request.go
- model_availability.go
- model_catalog_backend.go
- model_registry_facade.go
- model_resolver.go
- model_runtime_classify.go
- model_runtime_create.go
- model_runtime_members.go
- model_runtime_native.go
- model_runtime_selector.go
- model_runtime_typed.go
- model_stream_forwarding.go
- native_provider.go
- nested_tool_calls.go
- registered_stream_provider.go
- resource_loader.go
- resource_loader_extend.go
- resource_loader_extension_files.go
- runtime.go
- runtime_replacement.go
- services.go
- services_extension_runtime.go
- session.go
- session_bind.go
- session_boundaries.go
- session_cache_warming.go
- session_compaction_extensions.go
- session_custom_entries.go
- session_custom_messages.go
- session_event_barrier.go
- session_event_hold.go
- session_extend_resources.go
- session_extension_core.go
- session_extension_hooks.go
- session_extension_host.go
- session_extension_loader_host.go
- session_extension_replacement.go
- session_graph.go
- session_graph_model_runtime.go
- session_graph_package_manager.go
- session_graph_resource_loader.go
- session_host_actions.go
- session_images.go
- session_import.go
- session_loadout.go
- session_manager.go
- session_model_cycle.go
- session_ops.go
- session_preflight.go
- session_prompt.go
- session_prompt_resources.go
- session_queue_events.go
- session_recovery.go
- session_replaced.go
- session_replicated_state.go
- session_retry_scheduler.go
- session_run_state.go
- session_scoped_models.go
- session_state.go
- session_summarization_auth.go
- session_tool_registry.go
- session_tools.go
- session_transcript.go
- session_tree.go
- settings.go
- tool_definitions.go
- upstream.go
- virtual_models.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cli is the pig command line as a library: Main runs it for an argument list, as Pi's main(args, options) does (main.ts:573).
|
Package cli is the pig command line as a library: Main runs it for an argument list, as Pi's main(args, options) does (main.ts:573). |
|
Package extension defines the contract every pig extension speaks.
|
Package extension defines the contract every pig extension speaks. |
|
builtin
Package builtin is the registry of upstream's built-in extensions that PiG implements natively: the `builtin:<name>` extension paths of codemode and tool-search (docs/specs/builtin-codemode-tool-search.md).
|
Package builtin is the registry of upstream's built-in extensions that PiG implements natively: the `builtin:<name>` extension paths of codemode and tool-search (docs/specs/builtin-codemode-tool-search.md). |
|
builtin/codemode
Package codemode is the built-in `codemode` extension: the tool that lets the model write JavaScript that calls other tools.
|
Package codemode is the built-in `codemode` extension: the tool that lets the model write JavaScript that calls other tools. |
|
builtin/toolsearch
Package toolsearch is the built-in `tool_search` extension: tool discovery with a BM25 ranker over tool metadata, shared by `searchTools()` in codemode scripts and the optional `tool_search` tool.
|
Package toolsearch is the built-in `tool_search` extension: tool discovery with a BM25 ranker over tool metadata, shared by `searchTools()` in codemode scripts and the optional `tool_search` tool. |
|
extensiontest
Package extensiontest provides test doubles for the extension.API surface.
|
Package extensiontest provides test doubles for the extension.API surface. |
|
factoryload
Package factoryload runs the compiled-in extension factories of a binary: Go code that the source of the binary's own main package passes to it by value (docs/specs/extension-factory-trust.md).
|
Package factoryload runs the compiled-in extension factories of a binary: Go code that the source of the binary's own main package passes to it by value (docs/specs/extension-factory-trust.md). |
|
host/cellpack
Package cellpack is the Piglet-Binary-side counterpart to the host's prebuilt-cell seam (runtimecell.PrebuiltResolver).
|
Package cellpack is the Piglet-Binary-side counterpart to the host's prebuilt-cell seam (runtimecell.PrebuiltResolver). |
|
host/fusepack
Package fusepack holds Go extensions fused into a Piglet Binary.
|
Package fusepack holds Go extensions fused into a Piglet Binary. |
|
host/inproc
Package inproc implements the in-process Go dispatch runner for extensions.
|
Package inproc implements the in-process Go dispatch runner for extensions. |
|
host/runtimecell
Package runtimecell builds and resolves packed extension runtime cells.
|
Package runtimecell builds and resolves packed extension runtime cells. |
|
host/subprocess
Package subprocess implements pig's out-of-process extension transport: extensions communicate over a local stream socket with length-prefixed JSON framing.
|
Package subprocess implements pig's out-of-process extension transport: extensions communicate over a local stream socket with length-prefixed JSON framing. |
|
host/subprocess/internal/noderuntimegen
command
Command noderuntimegen packages the Node runtime and its content identity reproducibly.
|
Command noderuntimegen packages the Node runtime and its content identity reproducibly. |
|
host/subprocess/internal/noderuntimepack
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks.
|
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks. |
|
host/subprocess/internal/noderuntimepeers
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules.
|
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules. |
|
host/tsruntime
Package tsruntime selects the runtime that runs PiG's TypeScript and JavaScript extension host.
|
Package tsruntime selects the runtime that runs PiG's TypeScript and JavaScript extension host. |
|
installresolver
Package installresolver is Pig's product-neutral seam for contributed package-source behavior.
|
Package installresolver is Pig's product-neutral seam for contributed package-source behavior. |
|
markdowntransform
Package markdowntransform holds the display-only Markdown transformer contract and its chain.
|
Package markdowntransform holds the display-only Markdown transformer contract and its chain. |
|
pigsdk
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary.
|
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary. |
|
source
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition.
|
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition. |
|
Package extensionset holds the in-process half of the extension set DefaultResourceLoader loads: the inline and built-in extension factories (resource-loader.ts loadExtensionFactories, loadExtensionPaths' `builtin:` branch) and omitReplacedExtensions.
|
Package extensionset holds the in-process half of the extension set DefaultResourceLoader loads: the inline and built-in extension factories (resource-loader.ts loadExtensionFactories, loadExtensionPaths' `builtin:` branch) and omitReplacedExtensions. |
|
Package hookconfig parses and validates command hook files shared by Package validation and the runtime hook bridge.
|
Package hookconfig parses and validates command hook files shared by Package validation and the runtime hook bridge. |
|
Package mcpext is the built-in MCP integration (`builtin:mcp`).
|
Package mcpext is the built-in MCP integration (`builtin:mcp`). |
|
Ports packages/coding-agent/src/core/package-manager.ts.
|
Ports packages/coding-agent/src/core/package-manager.ts. |
|
Package piglet provides piglet-based capability scoping for pig sessions.
|
Package piglet provides piglet-based capability scoping for pig sessions. |
|
artifact
Package artifact defines executable Piglet component plans and artifact records.
|
Package artifact defines executable Piglet component plans and artifact records. |
|
internal/genstripids
command
Command genstripids writes internal/pigstrip/ids_generated.go, the table of stable IDs a Piglet strip list may name.
|
Command genstripids writes internal/pigstrip/ids_generated.go, the table of stable IDs a Piglet strip list may name. |
|
release
Package release verifies and installs signed Piglet Binary releases.
|
Package release verifies and installs signed Piglet Binary releases. |
|
signature
Package signature signs and verifies Piglet Binaries.
|
Package signature signs and verifies Piglet Binaries. |
|
Package pigletbuild validates Piglet closure and builds source or binary Piglet artifacts.
|
Package pigletbuild validates Piglet closure and builds source or binary Piglet artifacts. |
|
binarypiglet
Package binarypiglet holds the Piglet and resolution record embedded in a Piglet Binary.
|
Package binarypiglet holds the Piglet and resolution record embedded in a Piglet Binary. |
|
Package piglogin is PiG's built-in sprite login: the sprite's 16-by-14 pig, which the startup header shows in Pi's logo slot, the full login art (the 12-pixel "PiG." hero wordmark with its drop shadow beside that pig) that /sprite preview shows, the sprites `/sprite` chooses from, and the selection kept under $PIG_HOME/state/pig-standard/login.json.
|
Package piglogin is PiG's built-in sprite login: the sprite's 16-by-14 pig, which the startup header shows in Pi's logo slot, the full login art (the 12-pixel "PiG." hero wordmark with its drop shadow beside that pig) that /sprite preview shows, the sprites `/sprite` chooses from, and the selection kept under $PIG_HOME/state/pig-standard/login.json. |
|
Ports packages/coding-agent/src/modes/rpc/jsonl.ts
|
Ports packages/coding-agent/src/modes/rpc/jsonl.ts |
|
Package secretresolver provides the product-neutral resolver seam for typed Piglet secret refs.
|
Package secretresolver provides the product-neutral resolver seam for typed Piglet secret refs. |
|
Package source parses the source-reference vocabulary shared by package installation and Pig piglet resource origins.
|
Package source parses the source-reference vocabulary shared by package installation and Pig piglet resource origins. |