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.NewServices(coding.ServicesOptions{
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 and UpstreamCommit are the exact upstream Pi pins. The CLI, parity runner, source mirror, generated inventories, and Pig Porter consume them. Change both together, in internal/coding/pigversion/pigversion.go, then run the upgrade workflow in piglets/porter/skills/pig-porter/SKILL.md.
Index ¶
- Constants
- Variables
- func AcknowledgeEvent(event agent.AgentEvent) bool
- func BridgeNewRunnerTools(rts []extension.RegisteredTool) ([]agent.AgentTool, []error)
- func BuildModel(spec string, svcs *Services) (*ai.Model, error)
- func BuildModelFromEntry(providerID, modelID string, entry icodingagent.ModelEntry, svcs *Services) (*ai.Model, error)
- func BuildNativeModel(registry *icodingagent.ModelRegistry, providerID, modelID string) *ai.Model
- func BuildUserContent(text string, images []ai.ImageContent) ai.UserContentBlocks
- func CreateVirtualModel(definition VirtualModelDefinition) *ai.Model
- func DefaultAgentDir() string
- func ExtensionToolStartsActive(definition extension.ToolDefinition, allowed map[string]struct{}) bool
- func FindLatestResponse(messages []agent.AgentMessage) *agent.AssistantMessage
- func GetVirtualModelState(branch []icodingagent.SessionEntry, provider, modelID string) json.RawMessage
- func IsVirtualAPI(api ai.API) bool
- func IsVirtualModel(model *ai.Model) bool
- type AgentsFilesResult
- type BashResult
- type BranchSummaryEntry
- type CompactionResult
- type ContextFile
- type CreateAgentSessionRuntimeFactory
- type CreateAgentSessionRuntimeOptions
- type CreateAgentSessionRuntimeResult
- type CreateModelRuntimeOptions
- type CredentialSynchronizationError
- type CredentialSynchronizationOperation
- type DefaultResourceLoader
- func (l *DefaultResourceLoader) GetAgentsFiles() AgentsFilesResult
- func (l *DefaultResourceLoader) GetAppendSystemPrompt() []string
- func (l *DefaultResourceLoader) GetPrompts() PromptsResult
- func (l *DefaultResourceLoader) GetSkills() SkillsResult
- func (l *DefaultResourceLoader) GetSystemPrompt() (string, bool)
- func (l *DefaultResourceLoader) Reload() error
- type DefaultResourceLoaderOptions
- type ExtensionBindings
- type ExtensionOAuthConfig
- type ForkMessage
- 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() []icodingagent.ModelEntry
- 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) RegisterProviderConfig(id string, config ProviderConfigInput) 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) GetAllModels(providerID ...string) []ai.AnyModel
- 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) 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() []*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) HasConfiguredAuth(providerID string) bool
- func (runtime *ModelRuntime) IsUsingOAuth(providerID string) bool
- func (runtime *ModelRuntime) IsUsingSubscription(providerID string) bool
- 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) 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) 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) UnregisterVirtualModel(provider, id string)
- 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 ResolveModelOptions
- type ResolvedRequestAuth
- type ResourceLoader
- type RoutedModel
- type Runtime
- func (rt *Runtime) CWD() string
- func (rt *Runtime) Close() error
- func (rt *Runtime) Continue(opts SessionStartOptions) (*Session, error)
- 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) 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() *Services
- 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 ...*extension.SwitchSessionOptions) (extension.CancelledResult, error)
- func (rt *Runtime) SwitchSessionWithCWD(ctx context.Context, path, cwdOverride string, ...) (extension.CancelledResult, error)
- func (rt *Runtime) SwitchSessionWithProjectTrust(ctx context.Context, path, cwdOverride string, ...) (extension.CancelledResult, error)
- type RuntimeForkResult
- type RuntimeOptions
- type ScopedModel
- type Services
- func (s *Services) AgentDir() string
- func (s *Services) Auth() *ai.AuthStorage
- func (s *Services) CWD() string
- func (s *Services) Close()
- func (s *Services) Credentials() ai.CredentialStore
- func (s *Services) ModelRuntime() *ModelRuntime
- func (s *Services) Registry() *ModelRegistry
- func (s *Services) Settings() Settings
- func (s *Services) SettingsManager() *SettingsManager
- type ServicesOptions
- 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) AppendCustomEntry(customType string, data any) (string, error)
- func (s *Session) AvailableThinkingLevels() []ai.ThinkingLevel
- func (s *Session) BeginModelChange(ctx context.Context, m *ai.Model, source extension.ModelSelectSource, ...) (func(), error)
- func (s *Session) BeginPreparedPrompt(ctx context.Context, p *PreparedPrompt) (*PreparedPromptRun, 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) 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) error
- func (s *Session) CompactForExtension(ctx context.Context, customInstructions string) (any, error)
- func (s *Session) CompactResult(ctx context.Context, customInstructions string) (*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.ThinkingLevel, error)
- func (s *Session) CycleToModel(m *ai.Model, options ...ModelMutationOptions) error
- func (s *Session) DiscardAddedDefaultTools()
- 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)
- func (s *Session) EmitSessionStartTransition(reason, previousSessionFile string)
- func (s *Session) Entries() []icodingagent.SessionEntry
- func (s *Session) Events() <-chan agent.AgentEvent
- func (s *Session) ExecuteBash(ctx context.Context, command string, excludeFromContext bool) (BashResult, error)
- func (s *Session) ExecuteBashWithOperations(ctx context.Context, command string, excludeFromContext bool, ...) (BashResult, error)
- func (s *Session) ExecuteBashWithUpdates(ctx context.Context, command string, excludeFromContext bool, ...) (BashResult, error)
- func (s *Session) ExtensionCommandActions() extension.CommandActions
- func (s *Session) ExtensionCompact(options *extension.CompactOptions)
- func (s *Session) ExtensionRunner() *inproc.Runner
- func (s *Session) ExtensionSetModel(ctx context.Context, model *ai.Model) (bool, 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) 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) HasPendingMessages() bool
- func (s *Session) HiddenDeclarations() map[string]struct{}
- 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) IsCompacting() bool
- func (s *Session) IsIdle() 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, summarize bool, ...) (icodingagent.NavigateTreeResult, error)
- func (s *Session) NewSession(parentSession string) error
- 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) ([]agent.AgentMessage, error)
- 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) RefreshContext()
- func (s *Session) RefreshTools() error
- func (s *Session) RefreshToolsAfterReload() error
- func (s *Session) ReloadExtensions(extensions []extension.Extension) (*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) 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) SendMessage(message extension.CustomMessageRef, options *extension.SendMessageOptions) error
- func (s *Session) SendUserMessage(ctx context.Context, content any, options *extension.SendUserMessageOptions) error
- func (s *Session) Services() *Services
- func (s *Session) SessionManager() *SessionManager
- func (s *Session) SessionName() string
- func (s *Session) SetActiveToolsByName(names []string)
- func (s *Session) SetAutoRetryEnabled(enabled bool) error
- 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(m *ai.Model, options ModelMutationOptions, dispatch func(func() error) error) 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) 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.ThinkingLevel, options ...ModelMutationOptions) error
- func (s *Session) Signal() context.Context
- func (s *Session) StartEvent() extension.SessionStartEvent
- func (s *Session) Steer(ctx context.Context, text string, images []ai.ImageContent, ...) (QueuedInputDisposition, error)
- func (s *Session) StreamModel(ctx context.Context, model *ai.Model, request ai.Context, ...) *ai.AssistantMessageEventStream
- func (s *Session) Subscribe(listener func(agent.AgentEvent)) func()
- func (s *Session) SummarizeForBugReport(ctx context.Context, hint string) (string, error)
- func (s *Session) SwitchSession(path string) error
- func (s *Session) SystemPrompt() string
- func (s *Session) ThinkingLevel() ai.ThinkingLevel
- 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) ValidatePromptModelAuth(ctx context.Context) error
- func (s *Session) WaitForIdle(ctx context.Context) error
- type SessionContextUsage
- 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 SystemPromptResources
- 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 release commit mirrored for UpstreamVersion.
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 Pi release whose behavior PiG targets.
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 ErrNoServices = errors.New("coding: nil Services")
ErrNoServices is returned by APIs that require a Services instance when the caller passed nil.
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 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 ¶
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.NewServices(...)
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 *Services) (*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 CreateVirtualModel ¶
func CreateVirtualModel(definition VirtualModelDefinition) *ai.Model
CreateVirtualModel builds the catalog entry of a virtual model.
upstream: virtual-models.ts:159-176 (createVirtualModel)
func DefaultAgentDir ¶
func DefaultAgentDir() string
DefaultAgentDir returns the default global agent config directory: $PIG_HOME/agent if PIG_HOME is set, else ~/.pig/agent. Mirrors the path-resolution logic the pig binary uses internally.
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 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)
Types ¶
type AgentsFilesResult ¶
type AgentsFilesResult struct {
AgentsFiles []ContextFile
}
AgentsFilesResult is a loader's context files.
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 CompactionResult ¶
type CompactionResult struct {
Summary string
FirstKeptEntryID string
TokensBefore int
EstimatedTokensAfter int
Usage *ai.Usage
Details any
}
CompactionResult is the result returned by manual compaction.
type ContextFile ¶
type ContextFile = icodingagent.ContextFile
ContextFile is a loaded project context file (AGENTS.md or CLAUDE.md).
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
// ProjectTrustUI is the UI a project trust prompt for CWD uses. Pi's projectTrustContext (main.ts createRuntime) carries it for a replacement that the interactive mode drives; the factory falls back to a headless context without it.
ProjectTrustUI extension.UIContext
}
CreateAgentSessionRuntimeOptions selects the destination log and cwd-bound factory inputs.
type CreateAgentSessionRuntimeResult ¶
type CreateAgentSessionRuntimeResult struct {
Session *Session
Services *Services
// 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 contains the constructed Session and its Services.
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.
type CredentialSynchronizationOperation ¶
type CredentialSynchronizationOperation = icodingagent.CredentialSynchronizationOperation
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 does not load extensions or themes, which the Extension Host and the interactive theme controller own. 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) 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) 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) Reload ¶
func (l *DefaultResourceLoader) Reload() 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.
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
// 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
AgentsFilesOverride func(AgentsFilesResult) AgentsFilesResult
SystemPromptOverride func(*string) *string
AppendSystemPromptOverride func([]string) []string
}
DefaultResourceLoaderOptions configures NewDefaultResourceLoader (resource-loader.ts DefaultResourceLoaderOptions). Extension, theme and inline-extension options belong to the Extension Host and are not part of this loader.
type ExtensionBindings ¶
type ExtensionBindings struct {
UIContext extension.UIContext
CommandContextActions extension.CommandActions
Mode extension.ExtensionMode
}
ExtensionBindings supplies mode-owned UI and command actions before session_start dispatch.
type ExtensionOAuthConfig ¶
type ExtensionOAuthConfig = icodingagent.ExtensionOAuthConfig
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 ModelCycleResult ¶
type ModelCycleResult struct {
Model *ai.Model
ThinkingLevel ai.ThinkingLevel
IsScoped bool
}
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 (*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() []icodingagent.ModelEntry
GetAll returns the full model catalog without resolving request credentials.
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) RegisterProviderConfig ¶
func (registry *ModelRegistry) RegisterProviderConfig(id string, config ProviderConfigInput) error
RegisterProviderConfig registers the core provider input; RegisterProvider retains the extension host's distinct Go registration 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 *Services) (*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) 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) 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) 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() []*ai.Model
GetModels returns metadata snapshots for the complete static and explicitly registered model catalog.
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) HasConfiguredAuth ¶
func (runtime *ModelRuntime) HasConfiguredAuth(providerID string) bool
HasConfiguredAuth reports the provider's configured auth from the registry's published state, without credential I/O. 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) 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) 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) 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.
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) 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 ModelSelection ¶
ModelSelection names a model by provider and id.
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 current model's image profile after before_agent_start has completed.
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 ResolveModelOptions ¶
type ResolveModelOptions struct {
Reason ModelRouteReason
ThinkingLevel ai.ThinkingLevel
// 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 ResolvedRequestAuth ¶
type ResolvedRequestAuth struct {
OK bool `json:"ok"`
APIKey *string `json:"apiKey,omitempty"`
Headers ai.ProviderHeaders `json:"headers,omitempty"`
BaseURL string `json:"baseUrl,omitempty"`
Env map[string]string `json:"env,omitempty"`
Error string `json:"error,omitempty"`
}
ResolvedRequestAuth is the compatibility result for a model's request credentials.
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
}
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 RoutedModel ¶
type RoutedModel struct {
Model *ai.Model
ThinkingLevel ai.ThinkingLevel
}
RoutedModel is the physical model and thinking level a virtual selection currently resolves to.
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.
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) 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)
Fork creates a new Session containing the selected active branch. The default position is before a user message; at retains the selected entry itself.
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) 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) 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 ...*extension.SwitchSessionOptions) (extension.CancelledResult, error)
SwitchSession loads and validates the destination before disposing the outgoing Session, then rebuilds its cwd-bound runtime.
func (*Runtime) SwitchSessionWithCWD ¶
func (rt *Runtime) SwitchSessionWithCWD(ctx context.Context, path, cwdOverride string, options ...*extension.SwitchSessionOptions) (extension.CancelledResult, error)
SwitchSessionWithCWD is SwitchSession with a working directory that replaces the Session's stored one when that directory no longer exists, as Pi's switchSession cwdOverride does.
func (*Runtime) SwitchSessionWithProjectTrust ¶
func (rt *Runtime) SwitchSessionWithProjectTrust(ctx context.Context, path, cwdOverride string, projectTrustUI func(cwd string) extension.UIContext, options ...*extension.SwitchSessionOptions) (extension.CancelledResult, error)
SwitchSessionWithProjectTrust is SwitchSessionWithCWD with Pi's projectTrustContextFactory (agent-session-runtime.ts:196-222): projectTrustUI receives the destination cwd and returns the UI the replacement's project trust prompt uses. A nil factory keeps the headless trust context.
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 NewServices.
// Required.
Services *Services
// 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
}
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.
type Services ¶
type Services 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 NewServices ¶
func NewServices(opts ServicesOptions) (*Services, error)
NewServices 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 (*Services) AgentDir ¶
AgentDir returns the global agent config directory (typically ~/.pig/agent or $PIG_HOME/agent).
func (*Services) Auth ¶
func (s *Services) 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 (*Services) CWD ¶
CWD returns the working directory this Services container was constructed with.
func (*Services) Close ¶
func (s *Services) Close()
Close 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 (*Services) Credentials ¶
func (s *Services) Credentials() ai.CredentialStore
Credentials returns the credential store backing model authentication: the auth.json store, or the CredentialStore passed to CreateModelRuntime.
func (*Services) ModelRuntime ¶
func (s *Services) ModelRuntime() *ModelRuntime
ModelRuntime returns the one runtime shared by every Session and extension registry facade created from these Services.
func (*Services) Registry ¶
func (s *Services) 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 (*Services) 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 (*Services) SettingsManager ¶
func (s *Services) SettingsManager() *SettingsManager
SettingsManager returns the underlying live settings reader, useful when callers need to call Reload() or inspect global vs project layers separately.
type ServicesOptions ¶
type ServicesOptions 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
}
ServicesOptions configures NewServices. All fields are optional; empty values resolve to sensible defaults (current working directory, $PIG_HOME/agent or ~/.pig/agent).
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 NewSession ¶
func NewSession(svcs *Services, 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) 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) AvailableThinkingLevels ¶
func (s *Session) AvailableThinkingLevels() []ai.ThinkingLevel
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) BeginPreparedPrompt ¶
func (s *Session) BeginPreparedPrompt(ctx context.Context, p *PreparedPrompt) (*PreparedPromptRun, error)
BeginPreparedPrompt commits preflight and claims the agent before returning its run. A busy agent rejects execution after acceptance; it is not serialized behind the old run.
func (*Session) BindExtensions ¶
func (s *Session) BindExtensions(ctx context.Context, bindings ...ExtensionBindings) error
BindExtensions applies optional mode bindings, awaits the configured session_start event and admits tools registered by its handlers before returning. 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) 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.
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 ¶
Compact runs manual compaction. It preserves the historical SDK behavior that reports an already-small Session through compaction_end without returning an error.
func (*Session) CompactForExtension ¶
CompactForExtension runs an extension's ctx.compact({ onComplete, onError }) and returns the result in upstream CompactionResult's JSON shape. Unlike Compact, a session with nothing to compact is an error: upstream's compact() rejects, and ctx.compact reports that through onError.
func (*Session) CompactResult ¶
func (s *Session) CompactResult(ctx context.Context, customInstructions string) (*CompactionResult, error)
CompactResult runs manual compaction and returns the generated result.
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.
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.ThinkingLevel, error)
CycleThinkingLevel advances through supported levels, returning an empty level for a non-reasoning model.
func (*Session) CycleToModel ¶
func (s *Session) CycleToModel(m *ai.Model, options ...ModelMutationOptions) error
CycleToModel applies a model-cycle selection, saving global model defaults only with Persist.
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) 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.
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.
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.
func (*Session) ExecuteBash ¶
func (s *Session) ExecuteBash(ctx context.Context, command string, excludeFromContext bool) (BashResult, error)
ExecuteBash runs cmd in a shell outside the LLM agent loop and records the result so the agent sees it on the next turn (unless excludeFromContext is set). Mirrors upstream executeBash + recordBashResult (agent-session.ts:2554-2630). When excludeFromContext is true the result is persisted as a `bashExecution` entry but dropped from LLM context by bashExecutionToText (the `!!cmd` semantics).
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) ExecuteBashWithOperations ¶
func (s *Session) ExecuteBashWithOperations(ctx context.Context, command string, excludeFromContext bool, onChunk func(string), operations extension.BashOperations, id *string) (BashResult, error)
ExecuteBashWithOperations executes Bash through custom operations or the local shell when operations is nil. It reports each output chunk to onChunk and then to Session listeners, with id as the optional correlation identifier.
func (*Session) ExecuteBashWithUpdates ¶
func (s *Session) ExecuteBashWithUpdates(ctx context.Context, command string, excludeFromContext bool, onChunk func(string)) (BashResult, error)
ExecuteBashWithUpdates executes Bash and reports each output chunk to the callback and then to Session listeners before returning.
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) 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) 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.
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) 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) HasPendingMessages ¶
HasPendingMessages reports whether steering or follow-up messages are queued (upstream hasPendingMessages: pendingMessageCount > 0).
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) 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) 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) IsStreaming ¶
IsStreaming reports whether an agent run, including its retries, compaction, and queued continuations, is active (upstream isStreaming).
func (*Session) LastAssistantText ¶
LastAssistantText returns the text of the most-recent non-aborted assistant message, or nil if no such message exists. Mirrors upstream getLastAssistantText (agent-session.ts:3045).
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) Model ¶
Model returns a snapshot of the current model pointer. Do not mutate the returned model; publish a replacement with SetModel instead.
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, summarize bool, customInstructions string) (icodingagent.NavigateTreeResult, error)
NavigateTreeHandle implements the icodingagent.InteractiveSessionHandle interface. Bridges to navigateTree using flat args (summarize bool, customInstructions string) instead of NavigateTreeOptions struct, matching the interface signature. Returns icodingagent.NavigateTreeResult (structurally identical to coding.NavigateTreeResult).
func (*Session) NewSession ¶
NewSession replaces the active Session with a fresh Session.
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 without holding the Session run lock. Hosts normalize images and admit the result after that await, so another prompt or queue operation may proceed while a handler is suspended.
func (*Session) Prompt ¶
func (s *Session) Prompt(ctx context.Context, text string, options ...*PromptOptions) ([]agent.AgentMessage, error)
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) 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) 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) ReloadExtensions ¶
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) 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 awaits prompt preparation before acceptance and agent admission. Its input has already passed command/input dispatch. Suspended preflight does not mark the Session streaming or hold its run lock. Once accepted, 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) 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) 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) 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) SetAutoRetryEnabled ¶
SetAutoRetryEnabled toggles the auto-retry setting. Mirrors upstream setAutoRetryEnabled (agent-session.ts:2538).
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(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.
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) 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.ThinkingLevel, 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.
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) 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) 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) 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 func(agent.AgentEvent)) 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.
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.ThinkingLevel
ThinkingLevel returns the effective reasoning level used for future calls.
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) 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. Interactive mode runs the same check before it starts a turn.
type SessionContextUsage ¶
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 *Services, 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.ThinkingLevel
// 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
// 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
// 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.
AllowedTools map[string]struct{}
// ActiveBuiltinTools, when non-nil, restricts which built-in coding
// tools are active. Unlike AllowedTools it does NOT gate caller/
// extension tools (opts.Tools). A name that is not a built-in activates
// the registered extension or SDK tool of that name, as the names of
// the defaultTools setting do (sdk.ts:264-269). Names the resolved
// defaultTools setting lists start active in its order; the others
// follow in registry order, then by name. nil uses the defaultTools
// setting or upstream's default [read, bash, edit, write]. grep/find/ls
// remain registered but inactive unless requested.
ActiveBuiltinTools map[string]struct{}
// 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.ThinkingLevel
// 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{}
// ActiveBuiltinTools, when non-nil, restricts which built-in coding tools
// are active (extension/extra tools are unaffected, and a name that is
// not a built-in activates the extension tool of that name). nil means all
// built-in tools. Mirrors upstream defaultActiveToolNames (sdk.ts:244):
// the CLI default is [read, bash, edit, write], so grep/find/ls are
// registered but inactive unless requested via --tools.
ActiveBuiltinTools map[string]struct{}
// 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 ServicesOptions.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 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 TreePreparation ¶
type TreePreparation struct {
TargetID string `json:"targetId"`
OldLeafID *string `json:"oldLeafId"`
CommonAncestorID *string `json:"commonAncestorId"`
EntriesToSummarize []icodingagent.SessionEntry `json:"entriesToSummarize"`
UserWantsSummary bool `json:"userWantsSummary"`
// CustomInstructions are the custom summarization instructions.
CustomInstructions string `json:"customInstructions,omitempty"`
// ReplaceInstructions makes CustomInstructions replace the default prompt.
ReplaceInstructions bool `json:"replaceInstructions,omitempty"`
// Label is the label to attach to the branch summary entry.
Label string `json:"label,omitempty"`
}
TreePreparation is the session_before_tree preparation (extensions types.ts TreePreparation). Extensions receive it 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
¶
- block_images.go
- bug_report.go
- doc.go
- extension_bridge.go
- model.go
- model_api_request.go
- model_availability.go
- model_catalog_backend.go
- model_registry_facade.go
- model_runtime_classify.go
- model_runtime_create.go
- model_runtime_native.go
- model_runtime_typed.go
- model_stream_forwarding.go
- native_provider.go
- nested_tool_calls.go
- registered_stream_provider.go
- resource_loader.go
- runtime.go
- runtime_replacement.go
- services.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_extension_core.go
- session_extension_hooks.go
- session_extension_replacement.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_retry_scheduler.go
- session_run_state.go
- session_scoped_models.go
- session_summarization_auth.go
- session_tool_registry.go
- session_tools.go
- session_transcript.go
- session_tree.go
- settings.go
- upstream.go
- virtual_models.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |
|
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. |
|
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. |
|
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 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. |
|
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. |