coding

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 35 Imported by: 3

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

View Source
const (
	CredentialSynchronizationLogin               = icodingagent.CredentialSynchronizationLogin
	CredentialSynchronizationLogout              = icodingagent.CredentialSynchronizationLogout
	CredentialSynchronizationSetRuntimeAPIKey    = icodingagent.CredentialSynchronizationSetRuntimeAPIKey
	CredentialSynchronizationRemoveRuntimeAPIKey = icodingagent.CredentialSynchronizationRemoveRuntimeAPIKey
)
View Source
const PigVersion = pigversion.PigVersion

PigVersion is PiG's release line. It advances independently of the upstream Pi target.

View Source
const UpstreamCommit = pigversion.UpstreamCommit

UpstreamCommit is the exact Pi release commit mirrored for UpstreamVersion.

View Source
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.

View Source
const UpstreamVersion = pigversion.UpstreamVersion

UpstreamVersion is the Pi release whose behavior PiG targets.

View Source
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.

Variables

View Source
var ErrNoServices = errors.New("coding: nil Services")

ErrNoServices is returned by APIs that require a Services instance when the caller passed nil.

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

func BuildModel(spec string, svcs *Services) (*ai.Model, error)

BuildModel constructs an *ai.Model from a "provider/model" spec string, using the given Services for auth and registry lookup. The test-faux backend reuses one provider per Services container so tool-call counters survive request preparation.

Recognised provider prefixes:

  • "github-copilot/<model>" : uses the OAuth token in auth.json
  • "openai/<model>" : OPENAI_API_KEY (or registry override)
  • "openrouter/<model>" : OPENROUTER_API_KEY
  • "groq/<model>" : GROQ_API_KEY
  • "ollama/<model>" : OLLAMA_HOST or http://localhost:11434/v1
  • any other "<id>/<model>" : treated as OpenAI-compatible; API key from <ID_UPPER>_API_KEY env var

A bare "<model>" with no slash is interpreted as "openai/<model>" for backward compatibility with environments that hardcode OpenAI.

The catalog (context window, cost, capabilities) is resolved via ai.LookupModel; if the spec isn't in the codegen registry, the returned Model still works but has empty cost/window data (status-line just shows blank context %).

Library consumers can use this to construct models without hand-rolling provider switching:

svcs, _ := coding.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 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.

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

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
	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 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

type ForkMessage struct {
	EntryID string `json:"entryId"`
	Text    string `json:"text"`
}

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) 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) 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) GetError

func (registry *ModelRegistry) GetError() string

GetError returns the current model configuration diagnostic, or an empty string.

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) 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.

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) 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) 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) 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) GetModels

func (runtime *ModelRuntime) GetModels() []*ai.Model

GetModels returns metadata snapshots for the complete static and explicitly registered model catalog.

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) 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) (ai.Credential, error)

Login awaits same-provider credential operations, native authentication, and local synchronization. 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) 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. Native and caller-owned callbacks receive source options; only registry-built stock API leaves lower simple options.

type NavigateTreeOptions struct {
	// Summarize, when true, generates a branch summary for the branch being
	// left before navigating. Mirrors upstream navigateTree summarize flag.
	Summarize bool
	// CustomInstructions are forwarded to the branch summarizer prompt.
	CustomInstructions string
	// ReplaceInstructions, when true, makes CustomInstructions replace the
	// default summary prompt instead of being appended to it.
	ReplaceInstructions bool
	// Label is attached to the branch summary entry, or to the target entry
	// when no summary is created.
	Label string
}

NavigateTreeOptions controls Session.NavigateTree behaviour.

type NavigateTreeResult struct {
	EditorText string
	Cancelled  bool
	Aborted    bool
	// SummaryEntry is the branch_summary entry created by the navigation, or
	// nil when none was created.
	SummaryEntry *BranchSummaryEntry
}

NavigateTreeResult is the return value of Session.NavigateTree.

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 PromptOptions

type PromptOptions struct {
	ExpandPromptTemplates *bool
	Images                []ai.ImageContent
	StreamingBehavior     extension.DeliverAs
	Source                extension.InputSource
	PreflightResult       func(bool)
}

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 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 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) CWD

func (rt *Runtime) CWD() string

CWD returns the current Session's Services directory.

func (*Runtime) Close

func (rt *Runtime) Close() error

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

func (rt *Runtime) EmitQuitShutdownContext(ctx context.Context)

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

func (rt *Runtime) NewExtensionRunner() *inproc.Runner

NewExtensionRunner returns the extension runner.

func (*Runtime) NewSession

NewSession tears down the outgoing Session and creates a fresh Session through the retained factory. Cancellation precedes all replacement work.

func (*Runtime) Open

func (rt *Runtime) Open(path string, opts SessionStartOptions) (*Session, error)

Open loads an existing Session by path.

func (*Runtime) Resume

func (rt *Runtime) Resume(id string, opts SessionStartOptions) (*Session, error)

Resume loads an existing Session by id.

func (*Runtime) Services

func (rt *Runtime) Services() *Services

Services returns the underlying dependency container.

func (*Runtime) Session

func (rt *Runtime) Session() *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

func (rt *Runtime) SetBeforeSessionReplacement(drain func(context.Context) error)

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

func (rt *Runtime) SetRebindSession(rebind func(context.Context, *Session) error)

SetRebindSession installs the awaited host rebind callback. Configure it before starting replacement operations.

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

	// 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

func (s *Services) AgentDir() string

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

func (s *Services) CWD() string

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

func (s *Services) Settings() Settings

Settings returns the currently merged settings (global ⊕ project). This is a snapshot; call Settings() again to pick up changes after settings files are edited externally.

func (*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

func (s *Session) Abort(ctx context.Context) error

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

func (s *Session) ActiveToolNames() []string

ActiveToolNames returns the names of the tools active for the next agent turn. Mirrors upstream AgentSession.getActiveToolNames.

func (*Session) Agent

func (s *Session) Agent() *agent.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) 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) CWD

func (s *Session) CWD() string

CWD returns the working directory the session was created with.

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) CheckPromptCompaction

func (s *Session) CheckPromptCompaction(ctx context.Context) error

CheckPromptCompaction runs prompt()'s compaction check before a new user message, for a mode that starts the run itself with RunAgentPrompt.

func (*Session) ClearQueue

func (s *Session) ClearQueue() (steering, followUp []string)

ClearQueue removes and returns all queued user-message text.

func (*Session) Clone

func (s *Session) Clone() (*Session, error)

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

func (s *Session) CloneInPlace() error

CloneInPlace duplicates the active branch and switches to the clone.

func (*Session) Close

func (s *Session) Close() error

Close invalidates the extension runner this Session owns and releases the Session's resources without deleting its persisted JSONL. A runner borrowed from its Runtime or Clone source stays active; Runtime.Close invalidates the Runtime runner. Further Send calls fail; repeated Close calls are safe.

func (*Session) Compact

func (s *Session) Compact(ctx context.Context, customInstructions string) error

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

func (s *Session) CompactForExtension(ctx context.Context, customInstructions string) (any, error)

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) DispatchSlash

func (s *Session) DispatchSlash(line string) ([]string, error)

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

func (s *Session) EmitSessionShutdown(reason string)

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

func (s *Session) EmitSessionShutdownTransition(reason, targetSessionFile string)

EmitSessionShutdownTransition dispatches session_shutdown with the target Session file when a runtime host changes Sessions.

func (*Session) EmitSessionStart

func (s *Session) EmitSessionStart(reason string)

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

func (s *Session) EmitSessionStartTransition(reason, previousSessionFile string)

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) ExtensionRunner

func (s *Session) ExtensionRunner() *inproc.Runner

ExtensionRunner returns the Session's current extension runner, which reload and replacement change.

func (*Session) FlushEvents

func (s *Session) FlushEvents(ctx context.Context) error

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) 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

func (s *Session) Fork(entryID string) error

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

func (s *Session) ForkToNewSession(userMsgEntryID string) error

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

func (s *Session) ForkToNewSessionWithText(userMsgEntryID string) (string, error)

ForkToNewSessionWithText forks before a user message, switches this Session to the new file, and returns the selected message text.

func (*Session) GetAllTools

func (s *Session) GetAllTools() []extension.ToolInfo

GetAllTools returns every admitted definition, including inactive builtins, with its registration metadata.

func (*Session) GetFollowUpMessages

func (s *Session) GetFollowUpMessages() []string

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

func (s *Session) GetSteeringMessages() []string

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

func (s *Session) HasPendingMessages() bool

HasPendingMessages reports whether steering or follow-up messages are queued (upstream hasPendingMessages: pendingMessageCount > 0).

func (*Session) ID

func (s *Session) ID() string

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

func (s *Session) IsCompacting() bool

IsCompacting reports whether compaction or tree navigation is currently in flight.

func (*Session) IsIdle

func (s *Session) IsIdle() bool

IsIdle reports whether the session has no active run and no compaction in flight (upstream isIdle).

func (*Session) IsStreaming

func (s *Session) IsStreaming() bool

IsStreaming reports whether an agent run, including its retries, compaction, and queued continuations, is active (upstream isStreaming).

func (*Session) LastAssistantText

func (s *Session) LastAssistantText() *string

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

func (s *Session) LeafID() *string

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

func (s *Session) Model() *ai.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

func (s *Session) NewSession(parentSession string) error

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) Path

func (s *Session) Path() string

Path returns the absolute path to the session's JSONL file on disk.

func (*Session) PendingMessageCount

func (s *Session) PendingMessageCount() int

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) 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

func (s *Session) RefreshTools() error

RefreshTools rebuilds registered definitions and their prompt contributions, preserves active selection, and activates newly admitted names.

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

func (s *Session) ReplaceRunner(runner *inproc.Runner)

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) 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

func (s *Session) Send(ctx context.Context, prompt string) ([]agent.AgentMessage, error)

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) Services

func (s *Session) Services() *Services

Services returns the parent Services container.

func (*Session) SessionManager

func (s *Session) SessionManager() *SessionManager

SessionManager returns the backing log. A supplied manager is used directly; appends through either handle are visible through the other.

func (*Session) SessionName

func (s *Session) SessionName() string

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

func (s *Session) SetActiveToolsByName(names []string)

SetActiveToolsByName activates registered tools in the requested order and ignores unknown 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

func (s *Session) SetAutoRetryEnabled(enabled bool) error

SetAutoRetryEnabled toggles the auto-retry setting. Mirrors upstream setAutoRetryEnabled (agent-session.ts:2538).

func (*Session) SetBeforeSessionReplacement

func (s *Session) SetBeforeSessionReplacement(drain func(context.Context) error)

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

func (s *Session) SetFollowUpMode(mode agent.QueueMode) error

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

func (s *Session) SetName(name string) error

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

func (s *Session) SetRebindSession(rebind func(context.Context, extension.SessionStartEvent) error)

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

func (s *Session) SetSessionName(name string) error

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

func (s *Session) SetSteeringMode(mode agent.QueueMode) error

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) 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) 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

func (s *Session) SummarizeForBugReport(ctx context.Context, hint string) (string, error)

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

func (s *Session) SwitchSession(path string) error

SwitchSession loads a Session file and makes it active.

func (*Session) SystemPrompt

func (s *Session) SystemPrompt() string

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) Tools

func (s *Session) Tools() []agent.AgentTool

Tools returns a defensive copy of the active loadout. Use GetAllTools for admitted definitions that are currently inactive.

func (*Session) Tree

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

func (s *Session) ValidatePromptModelAuth(ctx context.Context) error

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.

func (*Session) WaitForIdle

func (s *Session) WaitForIdle(ctx context.Context) error

WaitForIdle blocks until the session is idle, ctx ends, or the session closes (upstream waitForIdle). A pending wait releases unawaited handler admission after its synchronous setup.

type SessionContextUsage

type SessionContextUsage struct {
	Tokens        *int     `json:"tokens"`
	ContextWindow int      `json:"contextWindow"`
	Percent       *float64 `json:"percent"`
}

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). 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). 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.

Directories

Path Synopsis
Package extension defines the contract every pig extension speaks.
Package extension defines the contract every pig extension speaks.
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.
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.
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.

Jump to

Keyboard shortcuts

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