agent

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 53 Imported by: 0

Documentation

Overview

Package agent provides the high-level SDK for embedding pi's agent capabilities in Go programs.

The primary entry point is NewAgentSession, which creates a fully configured AgentSession from an AgentSessionOptions struct. The returned session supports [AgentSession.Prompt], [AgentSession.Subscribe], and [AgentSession.SubscribeChan] for event-driven interaction with the underlying agent.

See docs/sdk.md for usage patterns and the examples/ directory for runnable programs covering minimal, custom-model, tools, settings, session management, and full-control configurations.

Index

Constants

View Source
const (
	CompactionSummaryPrefix = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n"
	CompactionSummarySuffix = "\n</summary>"
	BranchSummaryPrefix     = "The following is a summary of a branch that this conversation came back from:\n\n<summary>\n"
	BranchSummarySuffix     = "</summary>"
)

Variables

View Source
var BuiltinSlashCommands = []BuiltinSlashCommand{
	{Name: "settings", Description: "Open settings menu"},
	{Name: "model", Description: "Select model (opens selector UI)", ArgumentHint: "<provider/model>"},
	{Name: "tree", Description: "Navigate session tree (switch branches)"},
	{Name: "thinking", Description: "Set thinking level", ArgumentHint: "<level>"},
	{Name: "scoped-models", Description: "Enable/disable models for Ctrl+P cycling"},
	{Name: "export", Description: "Export session (HTML default, or specify path: .html/.jsonl)"},
	{Name: "import", Description: "Import and resume a session from a JSONL file"},
	{Name: "share", Description: "Share session as a secret GitHub gist"},
	{Name: "copy", Description: "Copy last agent message to clipboard"},
	{Name: "name", Description: "Set session display name"},
	{Name: "session", Description: "Show session info and stats"},
	{Name: "changelog", Description: "Show changelog entries"},
	{Name: "hotkeys", Description: "Show all keyboard shortcuts"},
	{Name: "fork", Description: "Create a new fork from a previous user message"},
	{Name: "clone", Description: "Duplicate the current session at the current position"},
	{Name: "trust", Description: "Save project trust decision for future sessions"},
	{Name: "login", Description: "Configure provider authentication", ArgumentHint: "<provider>"},
	{Name: "logout", Description: "Remove provider authentication"},
	{Name: "new", Description: "Start a new session"},
	{Name: "compact", Description: "Manually compact the session context"},
	{Name: "resume", Description: "Resume a different session"},
	{Name: "reload", Description: "Reload keybindings, extensions, skills, prompts, themes, and context files"},
	{Name: "quit", Description: "Quit orb"},
}
View Source
var DefaultActiveToolNames = []string{"read", "bash", "edit", "write"}

DefaultActiveToolNames is the upstream default tool set.

View Source
var ErrSessionDisposed = errors.New("agent: session is disposed")

ErrSessionDisposed is returned instead of starting or queueing work on a session that SessionRuntime.Dispose has already torn down. Without it a straggler goroutine — a client that disconnected mid-turn, an RPC command still unwinding after EOF — spends model budget and persists a turn into a session whose listeners are already gone.

Functions

func AuthGuidanceDocPaths added in v0.5.0

func AuthGuidanceDocPaths() (providersDoc, modelsDoc string)

AuthGuidanceDocPaths exposes the auth-guidance doc pointers to the CLI and TUI so every login/model hint resolves docs the same way (upstream getDocsPath consumers in auth-guidance.ts and interactive-mode.ts).

func BuildSystemPrompt added in v0.5.0

func BuildSystemPrompt(options SystemPromptOptions) string

BuildSystemPrompt assembles the system prompt in upstream section order with Orb's D30 product identity.

func BuiltInToolPromptData added in v0.5.0

func BuiltInToolPromptData(toolNames []string) (map[string]string, []string)

BuiltInToolPromptData returns the prompt snippets and guidelines contributed by built-in tools, in active-tool order.

func ConvertToLLM added in v0.5.0

func ConvertToLLM(_ context.Context, messages engine.AgentMessages) (ai.MessageList, error)

ConvertToLLM preserves coding-agent messages in runtime state and projects them to provider messages only at the agent-loop boundary.

func ConvertToLLMWithBlockImages added in v0.5.0

func ConvertToLLMWithBlockImages(blockImages func() bool) engine.ConvertToLLMFunc

ConvertToLLMWithBlockImages projects coding-agent messages and dynamically applies the upstream images.blockImages setting at the provider boundary.

func DefaultAgentDir added in v0.5.0

func DefaultAgentDir() string

DefaultAgentDir returns the upstream global resource directory.

func DefaultAvailableModel added in v0.5.0

func DefaultAvailableModel(provider string, available []ai.Model) *ai.Model

DefaultAvailableModel returns the provider's pinned upstream default only when that exact model is available after authentication.

func DefaultModelIDForProvider added in v0.5.0

func DefaultModelIDForProvider(provider string) (string, bool)

DefaultModelIDForProvider reports the upstream defaultModelPerProvider entry for a provider so the interactive login completion can name the missing default in its diagnostics (upstream interactive-mode.ts completeProviderAuthentication). It lives here only because this is the package-internal seam owned by the login work; model_resolver.go owns the table itself.

func ExpandPromptTemplate added in v0.5.0

func ExpandPromptTemplate(text string, templates []PromptTemplate) string

ExpandPromptTemplate expands a matching slash template or returns text unchanged.

func ExpandSkillCommand added in v0.5.0

func ExpandSkillCommand(text string, skills []Skill) (string, error)

ExpandSkillCommand reads a skill on invocation so edits are visible without resource reload.

func FormatChangelog added in v0.5.0

func FormatChangelog(content string) string

FormatChangelog parses, oldest-first reverses, and tag-pins links exactly as the interactive upstream changelog command does.

func FormatNoModelsAvailableMessage added in v0.5.0

func FormatNoModelsAvailableMessage() string

FormatNoModelsAvailableMessage exposes upstream formatNoModelsAvailableMessage (auth-guidance.ts:14-16) to CLI callers.

func FormatSkillInvocation added in v0.5.0

func FormatSkillInvocation(skill Skill, additionalInstructions string) string

FormatSkillInvocation formats an already-loaded harness skill.

func FormatSkillsForPrompt added in v0.5.0

func FormatSkillsForPrompt(skills []Skill) string

FormatSkillsForPrompt emits the Agent Skills progressive-disclosure XML block.

func GetExtensionTempFolder added in v0.5.0

func GetExtensionTempFolder(agentDir string) (string, error)

GetExtensionTempFolder creates the 0700 temp extension folder.

func IsUnknownModel added in v0.5.0

func IsUnknownModel(model *ai.Model) bool

IsUnknownModel reports the Agent sentinel used when no model is selected.

func LoadProjectContextFiles added in v0.5.0

func LoadProjectContextFiles(cwd, agentDir string) ([]ContextFile, []ResourceDiagnostic)

LoadProjectContextFiles loads the global context file followed by one file per directory from the filesystem root through cwd.

func MarshalSessionEvent added in v0.5.0

func MarshalSessionEvent(event any) ([]byte, error)

func OpenBrowser added in v0.5.0

func OpenBrowser(target string)

OpenBrowser opens a URL or file in the platform browser/default handler (upstream utils/open-browser.ts openBrowser). The launch is non-blocking and best-effort: callers still present the target to the user, so launcher failures (for example a missing xdg-open) are swallowed rather than surfaced.

func ParseCommandArgs added in v0.5.0

func ParseCommandArgs(argsString string) []string

ParseCommandArgs tokenizes template arguments with upstream's deliberately small quote grammar.

func PreferredAvailableModel added in v0.5.0

func PreferredAvailableModel(available []ai.Model) *ai.Model

func ResolveModelScope added in v0.5.0

func ResolveModelScope(patterns []string, available []ai.Model) ([]ScopedModel, []ModelDiagnostic)

func ResolveProjectTrusted added in v0.5.0

func ResolveProjectTrusted(ctx context.Context, options ResolveProjectTrustedOptions) (bool, error)

ResolveProjectTrusted decides project trust: CLI override, then a decisive project_trust extension, then the saved store, then defaultProjectTrust, then the interactive prompt (untrusted when no UI is available).

func SubstituteArgs added in v0.5.0

func SubstituteArgs(content string, args []string) string

SubstituteArgs replaces all placeholders in one pass, so inserted values are never re-expanded.

Types

type AgentSession added in v0.5.0

type AgentSession = SessionRuntime

AgentSession is the public embedding type. It wraps the internal SessionRuntime and exposes the full agent lifecycle: prompting, event subscription, model/thinking management, compaction, and tree navigation.

type AgentSessionOptions added in v0.5.0

type AgentSessionOptions struct {
	// CWD is the working directory for tool execution and resource discovery.
	// Defaults to the SessionManager's CWD if set, else ".".
	CWD string

	// AgentDir is the global config directory (auth.json, models.json, skills,
	// extensions). Defaults to ~/.pi/agent.
	AgentDir string

	// Model selects the initial model. When nil, NewAgentSession restores the
	// session model, then tries the settings default and available models.
	Model *ai.Model

	// ThinkingLevel sets the initial thinking budget. Clamped to the model's
	// supported range. Zero value defaults to "medium" for reasoning models
	// or "off" otherwise.
	ThinkingLevel ai.ModelThinkingLevel

	// ScopedModels restricts model cycling (CycleModel) to this set.
	ScopedModels []ScopedModel

	// StreamFn provides the LLM streaming backend. Defaults to the built-in
	// provider dispatcher when nil.
	StreamFn engine.StreamFn

	// GetAPIKey resolves API keys at request time. With the default StreamFn,
	// a nil resolver is derived from ModelRegistry.
	GetAPIKey engine.GetAPIKeyFunc

	// GetRequestAuth resolves request-time auth (OAuth tokens, Copilot baseURL).
	// When set, takes precedence over GetAPIKey for API key resolution; with
	// the default StreamFn, a nil resolver is derived from ModelRegistry.
	GetRequestAuth engine.GetRequestAuthFunc

	// GetModelHeaders provides per-request headers (e.g. attribution).
	GetModelHeaders engine.GetModelHeadersFunc

	// AvailableModels returns all models the host considers available.
	// Used by CycleModel when ScopedModels is empty.
	AvailableModels func() []ai.Model

	// ModelRegistry provides model resolution, auth checking, available-model
	// discovery, and session model restoration. Created from AgentDir when nil.
	ModelRegistry *config.ModelRegistry

	// NoTools suppresses default tool construction:
	//   "all"     — start with no tools at all
	//   "builtin" — disable default built-ins but keep extension/custom tools
	NoTools string

	// Tools is an allowlist of tool names. When provided, only listed tools
	// are enabled. Applies to built-in, extension, and custom tools.
	// When nil, the default set (read, bash, edit, write) is used unless
	// NoTools changes that.
	Tools []string

	// ExcludeTools is a denylist of tool names. Applied after Tools.
	ExcludeTools []string

	// CustomTools registers additional tool definitions alongside built-ins.
	CustomTools []extensions.ToolDefinition

	// ToolOptions overrides per-tool construction options for built-in tools.
	// Nil fields keep local defaults; settings-derived fields (AutoResizeImages,
	// ShellPath, CommandPrefix) are still applied when unset on the override.
	//
	// The options — including the nested per-tool structs — are captured by
	// the session and re-read whenever tools are rebuilt (also by
	// extension-driven tool rebuilds); they must not be mutated after
	// NewAgentSession returns.
	ToolOptions *tools.ToolsOptions

	// SessionManager controls session persistence. When nil a persistent
	// session is created for CWD (matching upstream default).
	SessionManager *sessionstore.SessionManager

	// Settings controls compaction, retry, and other runtime behavior.
	// When nil a default SettingsManager is created for CWD.
	Settings *config.SettingsManager

	// Resources supplies context files, skills, prompt templates, and the
	// system prompt. ResourceLoader takes precedence when both are provided.
	Resources *Resources

	// ResourceLoader supplies reloadable resources and native extensions. When
	// nil with no Resources override, DefaultResourceLoader is used.
	ResourceLoader ResourceLoader

	// ExtensionRegistry holds registered extensions. When non-nil and
	// non-empty, extensions are bound to the session runtime.
	ExtensionRegistry *extensions.Registry

	// SessionStartEvent metadata emitted when extensions bind.
	SessionStartEvent *extensions.SessionStartEvent

	// DeferExtensionStart leaves session_start activation to
	// [SessionRuntime.BindExtensions]. Runtime hosts use it so setup and host
	// rebinding finish before extensions observe the new session.
	DeferExtensionStart bool

	// ProjectTrustContext is supplied by replacement hosts for the effective
	// CWD so a custom runtime factory can resolve project trust before loading
	// project-scoped services.
	ProjectTrustContext extensions.ProjectTrustContext

	// SlashResolver handles /command and /skill expansion. When nil it is
	// derived from discovered skills and prompt templates.
	SlashResolver *SlashResolver

	// Clock supplies JavaScript Date.now-compatible milliseconds for message
	// and runtime timestamps (agent loop and session runtime). Defaults to the
	// wall clock; embedders and deterministic tests inject a fixed clock. It
	// does not reach a SessionManager passed in by the caller — create that
	// with session.WithClock to pin persisted entry timestamps too.
	Clock func() int64

	// BuiltinToolPrompts overrides the system-prompt contribution of named
	// built-in tools for this session (a present zero value suppresses the
	// contribution). The extension session bridge uses it to mirror upstream's
	// createCodingTools surface, which carries bash's contribution only.
	BuiltinToolPrompts map[string]ToolPromptContribution
}

AgentSessionOptions configures NewAgentSession. Fields mirror upstream createAgentSession options; zero values select sensible defaults.

type AgentSessionResult added in v0.5.0

type AgentSessionResult struct {
	// Session is the created agent session, ready for prompting.
	Session *AgentSession

	// ExtensionRegistry is the extension registry used (may be nil if no
	// extensions were configured).
	ExtensionRegistry *extensions.Registry

	// ModelFallbackMessage is set when no model can be selected or when a
	// continued session's saved model cannot be restored.
	ModelFallbackMessage string

	// Services contains the cwd-bound services used to build Session.
	Services *AgentSessionServices

	// Diagnostics contains non-fatal creation issues for the host to present.
	Diagnostics []AgentSessionRuntimeDiagnostic
}

AgentSessionResult is returned by NewAgentSession.

func CreateAgentSessionFromServices added in v0.5.0

func CreateAgentSessionFromServices(options CreateAgentSessionFromServicesOptions) (*AgentSessionResult, error)

func NewAgentSession added in v0.5.0

func NewAgentSession(opts AgentSessionOptions) (*AgentSessionResult, error)

NewAgentSession creates a fully configured AgentSession. It mirrors upstream's createAgentSession: it creates the internal Agent, wires streaming, resolves model and thinking-level defaults from any existing session state, constructs built-in tools, and returns a ready-to-prompt session.

result, err := agent.NewAgentSession(agent.AgentSessionOptions{
    StreamFn:       provider.StreamSimple,
    SessionManager: sessionMgr,
    Model:          &model,
})
if err != nil { ... }
defer result.Session.Dispose()
result.Session.Prompt(ctx, "Hello")

type AgentSessionRuntime added in v0.5.0

type AgentSessionRuntime struct {
	// contains filtered or unexported fields
}

AgentSessionRuntime owns the active AgentSession and replaces it for session lifecycle operations.

func NewAgentSessionRuntime added in v0.5.0

func NewAgentSessionRuntime(
	ctx context.Context,
	options AgentSessionOptions,
	factory ...CreateAgentSessionRuntimeFactory,
) (*AgentSessionRuntime, error)

NewAgentSessionRuntime creates a replaceable session host. The optional factory is reused so embedders can recreate cwd-bound services.

func (*AgentSessionRuntime) CWD added in v0.5.0

func (runtime *AgentSessionRuntime) CWD() string

CWD returns the effective working directory of the active session.

func (*AgentSessionRuntime) Diagnostics added in v0.5.0

func (runtime *AgentSessionRuntime) Diagnostics() []AgentSessionRuntimeDiagnostic

Diagnostics returns a snapshot of the active runtime's non-fatal issues.

func (*AgentSessionRuntime) Dispose added in v0.5.0

func (runtime *AgentSessionRuntime) Dispose(ctx context.Context)

Dispose emits the quit lifecycle event and tears down the active session.

func (*AgentSessionRuntime) Fork added in v0.5.0

Fork replaces the active session with a branch rooted before or at entryID.

func (*AgentSessionRuntime) ImportFromJSONL added in v0.5.0

func (runtime *AgentSessionRuntime) ImportFromJSONL(
	ctx context.Context,
	inputPath string,
	cwdOverride string,
) (extensions.SessionReplacementResult, error)

ImportFromJSONL copies a session JSONL file into the active session directory and resumes it.

func (*AgentSessionRuntime) ModelFallbackMessage added in v0.5.0

func (runtime *AgentSessionRuntime) ModelFallbackMessage() string

ModelFallbackMessage returns the current session's model-restoration warning.

func (*AgentSessionRuntime) NewSession added in v0.5.0

NewSession replaces the active session with a fresh persisted or in-memory session.

func (*AgentSessionRuntime) Services added in v0.5.0

func (runtime *AgentSessionRuntime) Services() *AgentSessionServices

Services returns the active session's cwd-bound services.

func (*AgentSessionRuntime) Session added in v0.5.0

func (runtime *AgentSessionRuntime) Session() *AgentSession

Session returns the active session.

func (*AgentSessionRuntime) SetBeforeSessionInvalidate added in v0.5.0

func (runtime *AgentSessionRuntime) SetBeforeSessionInvalidate(callback func())

SetBeforeSessionInvalidate sets the synchronous callback run after session_shutdown and before the old extension context becomes stale.

func (*AgentSessionRuntime) SetRebindSession added in v0.5.0

func (runtime *AgentSessionRuntime) SetRebindSession(rebind func(*AgentSession) error)

SetRebindSession sets the callback run after each replacement is installed.

func (*AgentSessionRuntime) SwitchSession added in v0.5.0

SwitchSession resumes a JSONL session and replaces the active session.

type AgentSessionRuntimeDiagnostic added in v0.5.0

type AgentSessionRuntimeDiagnostic struct {
	Type    string
	Message string
}

AgentSessionRuntimeDiagnostic is a non-fatal issue collected while creating cwd-bound SDK services.

type AgentSessionRuntimeForkResult added in v0.5.0

type AgentSessionRuntimeForkResult struct {
	Cancelled    bool
	SelectedText *string
}

AgentSessionRuntimeForkResult describes a fork result.

type AgentSessionRuntimeSwitchOptions added in v0.5.0

type AgentSessionRuntimeSwitchOptions struct {
	CWDOverride                string
	WithSession                func(context.Context, extensions.ReplacedSessionContext) error
	ProjectTrustContextFactory func(string) extensions.ProjectTrustContext
}

AgentSessionRuntimeSwitchOptions configures AgentSessionRuntime.SwitchSession.

type AgentSessionServices added in v0.5.0

type AgentSessionServices struct {
	CWD               string
	AgentDir          string
	SettingsManager   *config.SettingsManager
	ModelRegistry     *config.ModelRegistry
	Resources         *Resources
	ResourceLoader    ResourceLoader
	ExtensionRegistry *extensions.Registry
	Diagnostics       []AgentSessionRuntimeDiagnostic
}

AgentSessionServices are the cwd-bound services used by one session instance. A replacement runtime exposes the newly resolved set after every switch, fork, or new-session operation.

func CreateAgentSessionServices added in v0.5.0

func CreateAgentSessionServices(options CreateAgentSessionServicesOptions) (*AgentSessionServices, error)

type AgentSettledEvent added in v0.5.0

type AgentSettledEvent struct{}

type AutoRetryEndEvent added in v0.5.0

type AutoRetryEndEvent struct {
	Success    bool    `json:"success"`
	Attempt    int     `json:"attempt"`
	FinalError *string `json:"finalError,omitempty"`
}

type AutoRetryStartEvent added in v0.5.0

type AutoRetryStartEvent struct {
	Attempt      int    `json:"attempt"`
	MaxAttempts  int    `json:"maxAttempts"`
	DelayMS      int64  `json:"delayMs"`
	ErrorMessage string `json:"errorMessage"`
}

type BashExecutionUpdateEvent added in v0.5.0

type BashExecutionUpdateEvent struct {
	ID    *string `json:"id,omitempty"`
	Delta string  `json:"delta"`
}

BashExecutionUpdateEvent streams one output chunk of a direct bash command. ID matches the originating command's id when one was provided.

type BuiltinSlashCommand added in v0.5.0

type BuiltinSlashCommand struct {
	Name         string
	Description  string
	ArgumentHint string
}

type CLIModelResult added in v0.5.0

type CLIModelResult struct {
	Model          *ai.Model
	ThinkingLevel  *ai.ModelThinkingLevel
	Warning, Error string
}

func ResolveCLIModel added in v0.5.0

func ResolveCLIModel(provider, pattern string, cliThinking *ai.ModelThinkingLevel, available []ai.Model, authChecks ...func(string) bool) CLIModelResult

ResolveCLIModel implements provider/id inference, fuzzy matching, and custom-id fallback.

type CompactionEndEvent added in v0.5.0

type CompactionEndEvent struct {
	Reason       string                         `json:"reason"`
	Result       *sessionstore.CompactionResult `json:"result,omitempty"`
	Aborted      bool                           `json:"aborted"`
	WillRetry    bool                           `json:"willRetry"`
	ErrorMessage *string                        `json:"errorMessage,omitempty"`
}

type CompactionStartEvent added in v0.5.0

type CompactionStartEvent struct {
	Reason string `json:"reason"`
}

type ConfiguredPackage added in v0.5.0

type ConfiguredPackage struct {
	Source        string `json:"source"`
	Scope         string `json:"scope"`
	Filtered      bool   `json:"filtered"`
	InstalledPath string `json:"installedPath,omitempty"`
}

type ContextFile added in v0.5.0

type ContextFile struct {
	Path    string
	Content string
}

ContextFile is inserted verbatim into the project_context prompt block.

type CreateAgentSessionFromServicesOptions added in v0.5.0

type CreateAgentSessionFromServicesOptions struct {
	Services          *AgentSessionServices
	SessionManager    *sessionstore.SessionManager
	SessionStartEvent *extensions.SessionStartEvent
	Model             *ai.Model
	ThinkingLevel     ai.ModelThinkingLevel
	ScopedModels      []ScopedModel
	Tools             []string
	ExcludeTools      []string
	NoTools           string
	CustomTools       []extensions.ToolDefinition
	ToolOptions       *tools.ToolsOptions
}

type CreateAgentSessionRuntimeFactory added in v0.5.0

type CreateAgentSessionRuntimeFactory func(context.Context, AgentSessionOptions) (*AgentSessionResult, error)

CreateAgentSessionRuntimeFactory recreates a session after new, resume, fork, and import operations. A nil factory uses NewAgentSession.

type CreateAgentSessionServicesOptions added in v0.5.0

type CreateAgentSessionServicesOptions struct {
	CWD                         string
	AgentDir                    string
	SettingsManager             *config.SettingsManager
	ModelRegistry               *config.ModelRegistry
	ResourceOptions             *ResourceOptions
	ResourceLoaderOptions       *DefaultResourceLoaderOptions
	ResourceLoaderReloadOptions *ResourceLoaderReloadOptions
	ExtensionRegistry           *extensions.Registry
	ExtensionFlagValues         map[string]any
}

type CustomMessage added in v0.5.0

type CustomMessage = extensions.CustomMessage

type DefaultResourceLoader added in v0.5.0

type DefaultResourceLoader struct {
	// contains filtered or unexported fields
}

func NewDefaultResourceLoader added in v0.5.0

func NewDefaultResourceLoader(options DefaultResourceLoaderOptions) (*DefaultResourceLoader, error)

func (*DefaultResourceLoader) ExtendResources added in v0.5.0

func (loader *DefaultResourceLoader) ExtendResources(paths ResourceExtensionPaths)

func (*DefaultResourceLoader) GetAgentsFiles added in v0.5.0

func (loader *DefaultResourceLoader) GetAgentsFiles() ResourceAgentsFilesResult

func (*DefaultResourceLoader) GetAppendSystemPrompt added in v0.5.0

func (loader *DefaultResourceLoader) GetAppendSystemPrompt() []string

func (*DefaultResourceLoader) GetAppendSystemPromptSources added in v0.5.0

func (loader *DefaultResourceLoader) GetAppendSystemPromptSources() []PromptSource

func (*DefaultResourceLoader) GetExtensions added in v0.5.0

func (loader *DefaultResourceLoader) GetExtensions() *extensions.Registry

func (*DefaultResourceLoader) GetPrompts added in v0.5.0

func (loader *DefaultResourceLoader) GetPrompts() ResourcePromptsResult

func (*DefaultResourceLoader) GetSkills added in v0.5.0

func (loader *DefaultResourceLoader) GetSkills() ResourceSkillsResult

func (*DefaultResourceLoader) GetSystemPrompt added in v0.5.0

func (loader *DefaultResourceLoader) GetSystemPrompt() *string

func (*DefaultResourceLoader) GetSystemPromptSource added in v0.5.0

func (loader *DefaultResourceLoader) GetSystemPromptSource() *PromptSource

func (*DefaultResourceLoader) GetThemes added in v0.5.0

func (loader *DefaultResourceLoader) GetThemes() ResourceThemesResult

func (*DefaultResourceLoader) Reload added in v0.5.0

func (loader *DefaultResourceLoader) Reload(ctx context.Context, reloadOptions *ResourceLoaderReloadOptions) error

type DefaultResourceLoaderOptions added in v0.5.0

type DefaultResourceLoaderOptions struct {
	CWD             string
	AgentDir        string
	SettingsManager *config.SettingsManager

	AdditionalSkillPaths          []string
	AdditionalPromptTemplatePaths []string
	AdditionalThemePaths          []string
	PackageSkillPaths             []string
	PackagePromptTemplatePaths    []string
	PackageThemePaths             []ResourcePath
	ExtensionFactories            []extensions.Factory
	ExtensionRegistry             *extensions.Registry
	NoExtensions                  bool
	NoSkills                      bool
	NoPromptTemplates             bool
	NoThemes                      bool
	NoContextFiles                bool
	SystemPrompt                  *string
	AppendSystemPrompt            []string

	SkillsOverride             func(ResourceSkillsResult) ResourceSkillsResult
	PromptsOverride            func(ResourcePromptsResult) ResourcePromptsResult
	ThemesOverride             func(ResourceThemesResult) ResourceThemesResult
	AgentsFilesOverride        func(ResourceAgentsFilesResult) ResourceAgentsFilesResult
	SystemPromptOverride       func(*string) *string
	AppendSystemPromptOverride func([]string) []string
}

type EntryAppendedEvent added in v0.5.0

type EntryAppendedEvent struct {
	Entry sessionstore.SessionEntry `json:"entry"`
}

type ExtensionAgentSessionService added in v0.5.0

type ExtensionAgentSessionService struct {
	// contains filtered or unexported fields
}

ExtensionAgentSessionService is the runtime behind the extension host's agent_session_v1 capability (and sdk_v1's sdk_resource_reload). It backs every SDK createAgentSession call with a real NewAgentSession child session:

  • Callbacks fire synchronously from inside Prompt (the whole turn runs inline in SessionRuntime), so every event the turn produces is delivered before Prompt's terminal result (events-before-terminal ordering).
  • Every session event is mirrored through OnEvent, and the messages/stats mirrors are updated live during the turn via the delta callbacks.
  • customTools that reference host-JS closures execute in the host process through AgentSessionCreateRequest.ExecuteTool; their JSON Schema parameters are validated (and coerced) by the agent loop before execute (D14) and `terminate: true` in a tool result ends the turn.
  • Provider quota/limit failures land in the mirrored assistant message as stopReason "error" with the provider's verbatim errorMessage; Prompt itself resolves.
  • Options.ModelRuntime is resolved through the request's ResolveModelRuntime seam and drives streaming, auth, and the available model set of the child session.
  • Options.Session.SessionInfoNames (appendSessionInfo calls queued before the session existed) are applied right after create.
  • Dispose aborts a running prompt before releasing the session.
  • ReloadResources reloads the shared resource loader the next CreateSession for the same cwd/agentDir/noExtensions key observes.
  • Model resolution and fallback ride the create result (ModelFallbackMessage + Model), never the event stream.

Install it at product startup with Manager.SetAgentSessionService.

func NewExtensionAgentSessionService added in v0.5.0

func NewExtensionAgentSessionService(options ExtensionAgentSessionServiceOptions) *ExtensionAgentSessionService

NewExtensionAgentSessionService creates the NewAgentSession-backed implementation of the extension host's AgentSessionService seam.

func (*ExtensionAgentSessionService) CreateSession added in v0.5.0

CreateSession maps one agent_session_create request onto NewAgentSession.

func (*ExtensionAgentSessionService) ReloadResources added in v0.5.0

ReloadResources backs DefaultResourceLoader.reload() over sdk_v1: it reloads the real shared resource set (skills, prompts, AGENTS.md context — never extensions when NoExtensions) that the next CreateSession for the same key observes.

type ExtensionAgentSessionServiceOptions added in v0.5.0

type ExtensionAgentSessionServiceOptions struct {
	// CWD is the fallback working directory when a create request carries none.
	CWD string
	// AgentDir is the fallback agent directory (auth.json, models.json,
	// skills). Defaults to DefaultAgentDir().
	AgentDir string
	// StreamFn overrides the streaming backend for every child session (used
	// by tests and embedders with their own provider dispatch). When nil,
	// sessions stream through the resolved model runtime's registry —
	// extension-registered providers included — or the default HTTP
	// dispatcher.
	StreamFn engine.StreamFn
	// Clock supplies Date.now-compatible milliseconds for message, runtime,
	// and persisted-session timestamps of every child session. Defaults to the
	// wall clock; deterministic replay tests inject a fixed clock.
	Clock func() int64
}

ExtensionAgentSessionServiceOptions configures the child-session runtime.

type FooterSnapshot added in v0.5.0

type FooterSnapshot struct {
	Display               engine.AgentDisplayState
	Tokens                SessionTokenTotals
	Cost                  float64
	ContextUsage          *harness.ContextUsage
	LatestCacheHitRate    float64
	HasLatestCacheHitRate bool
	AutoCompactEnabled    bool
}

type GitSource added in v0.5.0

type GitSource struct {
	Repo   string `json:"repo"`
	Host   string `json:"host"`
	Path   string `json:"path"`
	Ref    string `json:"ref,omitempty"`
	Pinned bool   `json:"pinned"`
}

GitSource is a parsed git package source.

func ParseGitURL added in v0.5.0

func ParseGitURL(source string) *GitSource

ParseGitURL parses a git source.

Rules:

  • With git: prefix, all historical shorthand forms are accepted.
  • Without git: prefix, only explicit protocol URLs are accepted.

type InputAction added in v0.5.0

type InputAction string
const (
	InputPass      InputAction = "pass"
	InputHandled   InputAction = "handled"
	InputTransform InputAction = "transform"
)

type InputResult added in v0.5.0

type InputResult struct {
	Action InputAction
	Text   string
}

type InteractiveModeSettings added in v0.5.0

type InteractiveModeSettings struct {
	InteractiveSettings
	AgentDir             string
	ProjectTrusted       bool
	GlobalThemePaths     []string
	ProjectThemePaths    []string
	ThemeSetting         string
	ImageAutoResize      bool
	BlockImages          bool
	EnableSkillCommands  bool
	Transport            ai.Transport
	HTTPIdleTimeoutMS    int64
	OutputPad            int
	ExternalEditor       string
	TreeFilterMode       string
	DefaultProjectTrust  string
	ShowTerminalProgress bool
	MermaidRenderingMode string
}

InteractiveModeSettings is the immutable startup/runtime configuration the TUI consumes in addition to the frequently read InteractiveSettings values.

type InteractiveSettings added in v0.5.0

type InteractiveSettings struct {
	QuietStartup           bool
	DoubleEscapeAction     string
	ClearOnShrink          bool
	HideThinkingBlock      bool
	ShowCacheMissNotices   bool
	ShowImages             bool
	ImageWidthCells        int
	ShowHardwareCursor     bool
	EditorPaddingX         int
	AutocompleteMaxVisible int
	SteeringMode           engine.QueueMode
	FollowUpMode           engine.QueueMode
}

InteractiveSettings is an immutable snapshot of the documented UI settings interactive mode reads (upstream docs/settings.md UI keys); the mutable SettingsManager itself is never exposed.

type LoadPromptTemplatesOptions added in v0.5.0

type LoadPromptTemplatesOptions struct {
	CWD             string
	AgentDir        string
	PromptPaths     []string
	IncludeDefaults bool
}

type LoadSkillsFromDirOptions added in v0.5.0

type LoadSkillsFromDirOptions struct {
	Dir    string
	Source string
}

type LoadSkillsOptions added in v0.5.0

type LoadSkillsOptions struct {
	CWD             string
	AgentDir        string
	SkillPaths      []string
	IncludeDefaults bool
}

type LoadSkillsResult added in v0.5.0

type LoadSkillsResult struct {
	Skills      []Skill
	Diagnostics []ResourceDiagnostic
}

func LoadSkills added in v0.5.0

func LoadSkills(options LoadSkillsOptions) LoadSkillsResult

LoadSkills loads default and explicit locations, keeping the first name collision.

func LoadSkillsFromDir added in v0.5.0

func LoadSkillsFromDir(options LoadSkillsFromDirOptions) LoadSkillsResult

LoadSkillsFromDir follows upstream's root-file and recursive SKILL.md discovery rules.

type MissingSessionCWDError added in v0.5.0

type MissingSessionCWDError struct {
	SessionFile string
	SessionCWD  string
	FallbackCWD string
}

MissingSessionCWDError reports a persisted session whose working directory no longer exists.

func (*MissingSessionCWDError) Error added in v0.5.0

func (failure *MissingSessionCWDError) Error() string

type MissingSourceAction added in v0.5.0

type MissingSourceAction string

MissingSourceAction answers the resolve-time "install missing?" prompt.

const (
	MissingSourceInstall MissingSourceAction = "install"
	MissingSourceSkip    MissingSourceAction = "skip"
	MissingSourceError   MissingSourceAction = "error"
)

type ModelCycleResult added in v0.5.0

type ModelCycleResult struct {
	Model         ai.Model              `json:"model"`
	ThinkingLevel ai.ModelThinkingLevel `json:"thinkingLevel"`
	IsScoped      bool                  `json:"isScoped"`
}

type ModelDiagnostic added in v0.5.0

type ModelDiagnostic struct {
	Type, Code, Message, Pattern string
}

ModelDiagnostic mirrors upstream ModelScopeDiagnostic; Code classifies the warning as "no-match" or "invalid-thinking-level" (model-resolver.ts).

type ModelMutationOptions added in v0.6.0

type ModelMutationOptions struct{ Persist bool }
type NavigateTreeOptions struct {
	Summarize           bool
	CustomInstructions  string
	ReplaceInstructions bool
	Label               string
}
type NavigateTreeResult struct {
	EditorText   string
	Cancelled    bool
	Aborted      bool
	SummaryEntry *sessionstore.SessionEntry
}

type PackageManager added in v0.5.0

type PackageManager struct {
	// contains filtered or unexported fields
}

func NewPackageManager added in v0.5.0

func NewPackageManager(options PackageManagerOptions) *PackageManager

func (*PackageManager) AddSourceToSettings added in v0.5.0

func (manager *PackageManager) AddSourceToSettings(source string, local bool) (bool, error)

AddSourceToSettings adds or updates the package entry; reports change.

func (*PackageManager) CheckForAvailableUpdates added in v0.5.0

func (manager *PackageManager) CheckForAvailableUpdates() []PackageUpdate

CheckForAvailableUpdates keeps the upstream-shaped best-effort API.

func (*PackageManager) CheckForPackageUpdates added in v0.5.0

func (manager *PackageManager) CheckForPackageUpdates(ctx context.Context) (PackageUpdateCheck, error)

CheckForPackageUpdates checks all installed, unpinned packages within ctx.

func (*PackageManager) GetInstalledPath added in v0.5.0

func (manager *PackageManager) GetInstalledPath(source, scope string) string

GetInstalledPath reports where the source is installed, or "".

func (*PackageManager) Install added in v0.5.0

func (manager *PackageManager) Install(source string, local bool) error

Install installs without persisting to settings.

func (*PackageManager) InstallAndPersist added in v0.5.0

func (manager *PackageManager) InstallAndPersist(source string, local bool) error

func (*PackageManager) ListConfiguredPackages added in v0.5.0

func (manager *PackageManager) ListConfiguredPackages() []ConfiguredPackage

func (*PackageManager) Remove added in v0.5.0

func (manager *PackageManager) Remove(source string, local bool) error

func (*PackageManager) RemoveAndPersist added in v0.5.0

func (manager *PackageManager) RemoveAndPersist(source string, local bool) (bool, error)

func (*PackageManager) RemoveSourceFromSettings added in v0.5.0

func (manager *PackageManager) RemoveSourceFromSettings(source string, local bool) (bool, error)

RemoveSourceFromSettings removes matching entries; reports change.

func (*PackageManager) Resolve added in v0.5.0

func (manager *PackageManager) Resolve(onMissing func(source string) (MissingSourceAction, error)) (*ResolvedPaths, error)

Resolve resolves all configured packages, settings entries, and auto-discovered resources. onMissing (nil = install) answers what to do for configured-but-uninstalled sources.

func (*PackageManager) ResolveExtensionSources added in v0.5.0

func (manager *PackageManager) ResolveExtensionSources(sources []string, local, temporary bool) (*ResolvedPaths, error)

ResolveExtensionSources resolves ad-hoc sources (the -e flag path).

func (*PackageManager) SetProgressCallback added in v0.5.0

func (manager *PackageManager) SetProgressCallback(callback ProgressCallback)

func (*PackageManager) Update added in v0.5.0

func (manager *PackageManager) Update(source string) error

Update updates all configured packages, or only those matching source.

func (*PackageManager) UpdateWithResults added in v0.5.0

func (manager *PackageManager) UpdateWithResults(source string) ([]PackageVersionUpdate, error)

UpdateWithResults runs Update unchanged and reports packages whose installed version or Git revision changed.

type PackageManagerOptions added in v0.5.0

type PackageManagerOptions struct {
	CWD      string
	AgentDir string
	Settings *config.SettingsManager
}

type PackageUpdate added in v0.5.0

type PackageUpdate struct {
	Source      string `json:"source"`
	DisplayName string `json:"displayName"`
	Type        string `json:"type"`
	Scope       string `json:"scope"`
}

type PackageUpdateCheck added in v0.5.0

type PackageUpdateCheck struct {
	Installed int
	Updates   []PackageVersionUpdate
}

type PackageVersionUpdate added in v0.5.0

type PackageVersionUpdate struct {
	PackageUpdate
	CurrentVersion string
	LatestVersion  string
}

type ParsedModel added in v0.5.0

type ParsedModel struct {
	Model         *ai.Model
	ThinkingLevel *ai.ModelThinkingLevel
	Warning       string
}

func ParseModelPattern added in v0.5.0

func ParseModelPattern(pattern string, available []ai.Model, allowInvalidFallback ...bool) ParsedModel

ParseModelPattern matches the complete id first so colons inside model ids remain literal.

type ParsedSkillBlock added in v0.5.0

type ParsedSkillBlock = exporthtml.ParsedSkillBlock

ParsedSkillBlock is an upstream skill invocation embedded in a user message.

func ParseSkillBlock added in v0.5.0

func ParseSkillBlock(text string) (ParsedSkillBlock, bool)

ParseSkillBlock parses the exact upstream skill-message envelope.

type PathMetadata added in v0.5.0

type PathMetadata struct {
	Source  string `json:"source"`
	Scope   string `json:"scope"`
	Origin  string `json:"origin"`
	BaseDir string `json:"baseDir,omitempty"`
}

PathMetadata mirrors upstream's resolved-resource metadata shape.

type ProgressCallback added in v0.5.0

type ProgressCallback func(ProgressEvent)

type ProgressEvent added in v0.5.0

type ProgressEvent struct {
	Type    string `json:"type"`
	Action  string `json:"action"`
	Source  string `json:"source"`
	Message string `json:"message,omitempty"`
}

type PromptOptions added in v0.5.0

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

type PromptSource added in v0.5.0

type PromptSource struct {
	Path string
}

PromptSource identifies a file-backed system prompt input.

type PromptTemplate added in v0.5.0

type PromptTemplate struct {
	Name         string
	Description  string
	ArgumentHint string
	Content      string
	SourceInfo   SourceInfo
	FilePath     string
}

PromptTemplate is a file-backed slash command expanded before a prompt is sent.

func LoadPromptTemplates added in v0.5.0

func LoadPromptTemplates(options LoadPromptTemplatesOptions) []PromptTemplate

LoadPromptTemplates discovers non-recursive markdown templates from default and explicit paths.

type QueueUpdateEvent added in v0.5.0

type QueueUpdateEvent struct {
	Steering []string `json:"steering"`
	FollowUp []string `json:"followUp"`
}

type ResolveProjectTrustedOptions added in v0.5.0

type ResolveProjectTrustedOptions struct {
	CWD           string
	TrustStore    *config.ProjectTrustStore
	TrustOverride *bool
	// "ask" (default), "always", or "never".
	DefaultProjectTrust string
	// Optional extension runner whose project_trust handlers may decide.
	Runner       *extensions.Runner
	TrustContext extensions.Context
	HasUI        bool
	// SelectOption shows the trust prompt and returns the chosen label; the
	// second result is false when the user dismissed the prompt.
	SelectOption     func(title string, options []string) (string, bool)
	OnExtensionError func(message string)
}

type ResolvedPaths added in v0.5.0

type ResolvedPaths struct {
	Extensions []ResolvedResource `json:"extensions"`
	Skills     []ResolvedResource `json:"skills"`
	Prompts    []ResolvedResource `json:"prompts"`
	Themes     []ResolvedResource `json:"themes"`
}

type ResolvedResource added in v0.5.0

type ResolvedResource struct {
	Path     string       `json:"path"`
	Enabled  bool         `json:"enabled"`
	Metadata PathMetadata `json:"metadata"`
}

type ResourceAgentsFilesResult added in v0.5.0

type ResourceAgentsFilesResult struct {
	AgentsFiles []ContextFile
}

type ResourceCollision added in v0.5.0

type ResourceCollision struct {
	ResourceType string
	Name         string
	WinnerPath   string
	LoserPath    string
}

type ResourceDiagnostic added in v0.5.0

type ResourceDiagnostic struct {
	Type      string
	Message   string
	Path      string
	Collision *ResourceCollision
}

type ResourceExtensionPaths added in v0.5.0

type ResourceExtensionPaths struct {
	SkillPaths  []ResourcePath
	PromptPaths []ResourcePath
	ThemePaths  []ResourcePath
}

type ResourceLoader added in v0.5.0

type ResourceLoader interface {
	GetExtensions() *extensions.Registry
	GetSkills() ResourceSkillsResult
	GetPrompts() ResourcePromptsResult
	GetThemes() ResourceThemesResult
	GetAgentsFiles() ResourceAgentsFilesResult
	GetSystemPrompt() *string
	GetSystemPromptSource() *PromptSource
	GetAppendSystemPrompt() []string
	GetAppendSystemPromptSources() []PromptSource
	ExtendResources(ResourceExtensionPaths)
	Reload(context.Context, *ResourceLoaderReloadOptions) error
}

ResourceLoader is the replaceable SDK resource seam used by AgentSession. Its method set mirrors upstream's ResourceLoader while keeping cancellation explicit for reloads.

type ResourceLoaderReloadOptions added in v0.5.0

type ResourceLoaderReloadOptions struct {
	ResolveProjectTrust func(context.Context, *extensions.Registry) (bool, error)
}

type ResourceOptions added in v0.5.0

type ResourceOptions struct {
	CWD               string
	AgentDir          string
	ProjectTrusted    *bool
	NoContextFiles    bool
	NoSkills          bool
	NoPromptTemplates bool
	SystemPrompt      *string
	// Nil means discover APPEND_SYSTEM.md; a non-nil empty slice disables discovery.
	AppendSystemPrompt         []string
	SkillPaths                 []string
	PromptTemplatePaths        []string
	GlobalSkillPaths           []string
	ProjectSkillPaths          []string
	GlobalPromptTemplatePaths  []string
	ProjectPromptTemplatePaths []string
	PackageSkillPaths          []string
	PackagePromptTemplatePaths []string
	SkillPathMetadata          map[string]PathMetadata
	PromptPathMetadata         map[string]PathMetadata
}

type ResourcePath added in v0.5.0

type ResourcePath struct {
	Path     string
	Metadata PathMetadata
}

type ResourcePromptsResult added in v0.5.0

type ResourcePromptsResult struct {
	Prompts     []PromptTemplate
	Diagnostics []ResourceDiagnostic
}

type ResourceSkillsResult added in v0.5.0

type ResourceSkillsResult struct {
	Skills      []Skill
	Diagnostics []ResourceDiagnostic
}

type ResourceThemesResult added in v0.5.0

type ResourceThemesResult struct {
	Themes      []*modetheme.Theme
	Diagnostics []ResourceDiagnostic
}

type Resources added in v0.5.0

type Resources struct {
	ContextFiles              []ContextFile
	SystemPrompt              *string
	SystemPromptSource        *PromptSource
	AppendSystemPrompt        []string
	AppendSystemPromptSources []PromptSource
	Skills                    []Skill
	PromptTemplates           []PromptTemplate
	Diagnostics               []ResourceDiagnostic
	// contains filtered or unexported fields
}

func LoadResources added in v0.5.0

func LoadResources(options ResourceOptions) Resources

LoadResources discovers context and prompt files, then applies CLI overrides.

func (Resources) JoinedAppendSystemPrompt added in v0.5.0

func (resources Resources) JoinedAppendSystemPrompt() *string

JoinedAppendSystemPrompt applies the separator used before prompt assembly.

type ScopedModel added in v0.5.0

type ScopedModel struct {
	Model         ai.Model
	ThinkingLevel *ai.ModelThinkingLevel
}

type SendCustomMessageOptions added in v0.5.0

type SendCustomMessageOptions = extensions.SendMessageOptions

type SendUserMessageOptions added in v0.5.0

type SendUserMessageOptions = extensions.SendUserMessageOptions

type SessionAgentEndEvent added in v0.5.0

type SessionAgentEndEvent struct {
	Messages  engine.AgentMessages `json:"messages"`
	WillRetry bool                 `json:"willRetry"`
}

type SessionEventType added in v0.5.0

type SessionEventType string
const (
	EventAgentSettled                   SessionEventType = "agent_settled"
	EventQueueUpdate                    SessionEventType = "queue_update"
	EventCompactionStart                SessionEventType = "compaction_start"
	EventCompactionEnd                  SessionEventType = "compaction_end"
	EventAutoRetryStart                 SessionEventType = "auto_retry_start"
	EventAutoRetryEnd                   SessionEventType = "auto_retry_end"
	EventSummarizationRetryScheduled    SessionEventType = "summarization_retry_scheduled"
	EventSummarizationRetryAttemptStart SessionEventType = "summarization_retry_attempt_start"
	EventSummarizationRetryFinished     SessionEventType = "summarization_retry_finished"
	EventBashExecutionUpdate            SessionEventType = "bash_execution_update"
	EventEntryAppended                  SessionEventType = "entry_appended"
	EventSessionInfo                    SessionEventType = "session_info_changed"
	EventThinkingLevel                  SessionEventType = "thinking_level_changed"
)

type SessionImportFileNotFoundError added in v0.5.0

type SessionImportFileNotFoundError struct {
	FilePath string
}

SessionImportFileNotFoundError reports a missing JSONL import source.

func (*SessionImportFileNotFoundError) Error added in v0.5.0

func (failure *SessionImportFileNotFoundError) Error() string

type SessionInfoChangedEvent added in v0.5.0

type SessionInfoChangedEvent struct {
	Name *string `json:"name,omitempty"`
}

type SessionRuntime added in v0.5.0

type SessionRuntime struct {
	// contains filtered or unexported fields
}

func NewSessionRuntime added in v0.5.0

func NewSessionRuntime(runtimeConfig SessionRuntimeConfig) (*SessionRuntime, error)

func (*SessionRuntime) Abort added in v0.5.0

func (runtime *SessionRuntime) Abort()

func (*SessionRuntime) AbortBash added in v0.5.0

func (runtime *SessionRuntime) AbortBash()

func (*SessionRuntime) AbortBranchSummary added in v0.5.0

func (runtime *SessionRuntime) AbortBranchSummary()

func (*SessionRuntime) AbortCompaction added in v0.5.0

func (runtime *SessionRuntime) AbortCompaction()

func (*SessionRuntime) AbortRetry added in v0.5.0

func (runtime *SessionRuntime) AbortRetry()

func (*SessionRuntime) Agent added in v0.5.0

func (runtime *SessionRuntime) Agent() *engine.Agent

func (*SessionRuntime) AutoCompactionEnabled added in v0.5.0

func (runtime *SessionRuntime) AutoCompactionEnabled() bool

func (*SessionRuntime) AutoRetryEnabled added in v0.5.0

func (runtime *SessionRuntime) AutoRetryEnabled() bool

func (*SessionRuntime) AvailableModels added in v0.5.0

func (runtime *SessionRuntime) AvailableModels() []ai.Model

func (*SessionRuntime) AvailableThinkingLevels added in v0.5.0

func (runtime *SessionRuntime) AvailableThinkingLevels() []ai.ModelThinkingLevel

func (*SessionRuntime) BindExtensionUI added in v0.5.0

func (runtime *SessionRuntime) BindExtensionUI(ui extensions.UI, mode extensions.Mode)

BindExtensionUI installs the extension UI seam on the active runner and in the stored runner configuration, so /reload rebuilds keep it. Upstream rpc-mode rebindSession passes its uiContext into bindExtensions on every rebind (rpc-mode.ts:311-320); this is the equivalent seam for Go hosts.

func (*SessionRuntime) BindExtensions added in v0.5.0

func (runtime *SessionRuntime) BindExtensions(ctx context.Context) error

BindExtensions activates the session's extension instance and emits its configured session_start event once.

func (*SessionRuntime) BindHostCommandActions added in v0.5.0

func (runtime *SessionRuntime) BindHostCommandActions(actions extensions.CommandActions)

func (*SessionRuntime) ClearQueue added in v0.5.0

func (runtime *SessionRuntime) ClearQueue() QueueUpdateEvent

func (*SessionRuntime) Commands added in v0.5.0

func (runtime *SessionRuntime) Commands() []SlashCommandInfo

func (*SessionRuntime) Compact added in v0.5.0

func (runtime *SessionRuntime) Compact(ctx context.Context, customInstructions string) (*sessionstore.CompactionResult, error)

func (*SessionRuntime) Continue added in v0.5.0

func (runtime *SessionRuntime) Continue(ctx context.Context) error

func (*SessionRuntime) CycleModel added in v0.5.0

func (runtime *SessionRuntime) CycleModel(ctx context.Context) (*ModelCycleResult, error)

func (*SessionRuntime) CycleModelBackward added in v0.5.0

func (runtime *SessionRuntime) CycleModelBackward(ctx context.Context) (*ModelCycleResult, error)

CycleModelBackward is upstream cycleModel("backward"): same scope selection, auth filtering, and thinking-level handling as CycleModel, stepping in reverse.

func (*SessionRuntime) CycleThinkingLevel added in v0.5.0

func (runtime *SessionRuntime) CycleThinkingLevel() (*ai.ModelThinkingLevel, error)

func (*SessionRuntime) DequeueMessages added in v0.5.0

func (runtime *SessionRuntime) DequeueMessages() []string

func (*SessionRuntime) Dispose added in v0.5.0

func (runtime *SessionRuntime) Dispose()

func (*SessionRuntime) EnabledModels added in v0.5.0

func (runtime *SessionRuntime) EnabledModels() []string

EnabledModels returns the persisted model-scope patterns (upstream settingsManager.getEnabledModels), which /models resolves with diagnostics so configured-but-unavailable ids stay editable.

func (*SessionRuntime) ExecuteBash added in v0.5.0

func (runtime *SessionRuntime) ExecuteBash(ctx context.Context, command string, excludeFromContext *bool) (tools.BashResult, error)

ExecuteBash executes a direct bash command.

func (*SessionRuntime) ExecuteBashWithID added in v0.5.0

func (runtime *SessionRuntime) ExecuteBashWithID(ctx context.Context, command string, excludeFromContext *bool, id *string) (tools.BashResult, error)

ExecuteBashWithID includes id in bash_execution_update events streamed for each output chunk.

func (*SessionRuntime) ExecuteUserBash added in v0.5.0

func (runtime *SessionRuntime) ExecuteUserBash(
	ctx context.Context,
	command string,
	excludeFromContext bool,
	onChunk func(string),
) (extensions.BashResult, error)

func (*SessionRuntime) ExecuteUserBashWithID added in v0.5.0

func (runtime *SessionRuntime) ExecuteUserBashWithID(
	ctx context.Context,
	command string,
	excludeFromContext *bool,
	id *string,
) (tools.BashResult, error)

func (*SessionRuntime) ExportHTML added in v0.5.0

func (runtime *SessionRuntime) ExportHTML(outputPath string) (string, error)

func (*SessionRuntime) ExportJSONL added in v0.5.0

func (runtime *SessionRuntime) ExportJSONL(outputPath string) (string, error)

ExportJSONL writes the current root-to-leaf branch as a standalone upstream session file, re-chaining parentId values into a linear sequence.

func (*SessionRuntime) ExtensionResources added in v0.5.0

func (runtime *SessionRuntime) ExtensionResources() extensions.DiscoveredResources

func (*SessionRuntime) ExtensionRunner added in v0.5.0

func (runtime *SessionRuntime) ExtensionRunner() *extensions.Runner

func (*SessionRuntime) FollowUp added in v0.5.0

func (runtime *SessionRuntime) FollowUp(text string) error

func (*SessionRuntime) FollowUpImages added in v0.5.0

func (runtime *SessionRuntime) FollowUpImages(text string, images []*ai.ImageContent) error

func (*SessionRuntime) FollowUpMode added in v0.5.0

func (runtime *SessionRuntime) FollowUpMode() engine.QueueMode

func (*SessionRuntime) FooterSnapshot added in v0.5.0

func (runtime *SessionRuntime) FooterSnapshot() FooterSnapshot

func (*SessionRuntime) GetActiveToolNames added in v0.5.0

func (runtime *SessionRuntime) GetActiveToolNames() []string

func (*SessionRuntime) GetContextUsage added in v0.5.0

func (runtime *SessionRuntime) GetContextUsage() *harness.ContextUsage

func (*SessionRuntime) GetLastAssistantText added in v0.5.0

func (runtime *SessionRuntime) GetLastAssistantText() *string

func (*SessionRuntime) GetSessionStats added in v0.5.0

func (runtime *SessionRuntime) GetSessionStats() SessionStats

func (*SessionRuntime) GetToolDefinition added in v0.5.0

func (runtime *SessionRuntime) GetToolDefinition(name string) *extensions.ToolDefinition

GetToolDefinition mirrors upstream AgentSession.getToolDefinition for extension tools: the registered ToolDefinition (including renderCall and renderResult) for name, or nil for built-in, unknown, or disallowed tools.

func (*SessionRuntime) GetUserMessagesForForking added in v0.5.0

func (runtime *SessionRuntime) GetUserMessagesForForking() []struct {
	EntryID string `json:"entryId"`
	Text    string `json:"text"`
}

func (*SessionRuntime) InteractiveModeSettings added in v0.5.0

func (runtime *SessionRuntime) InteractiveModeSettings() InteractiveModeSettings

func (*SessionRuntime) InteractiveSettings added in v0.5.0

func (runtime *SessionRuntime) InteractiveSettings() InteractiveSettings

func (*SessionRuntime) IsBashRunning added in v0.5.0

func (runtime *SessionRuntime) IsBashRunning() bool

func (*SessionRuntime) IsCompacting added in v0.5.0

func (runtime *SessionRuntime) IsCompacting() bool

func (*SessionRuntime) IsIdle added in v0.5.0

func (runtime *SessionRuntime) IsIdle() bool

func (*SessionRuntime) Manager added in v0.5.0

func (runtime *SessionRuntime) Manager() *sessionstore.SessionManager

func (*SessionRuntime) MermaidRenderingMode added in v0.5.0

func (runtime *SessionRuntime) MermaidRenderingMode() string

MermaidRenderingMode returns the settings-manager mermaid rendering mode ("off" | "final" | "streaming").

func (*SessionRuntime) NavigateTree added in v0.5.0

func (runtime *SessionRuntime) NavigateTree(ctx context.Context, targetID string, options NavigateTreeOptions) (NavigateTreeResult, error)

func (*SessionRuntime) PendingMessageCount added in v0.5.0

func (runtime *SessionRuntime) PendingMessageCount() int

func (*SessionRuntime) PendingMessages added in v0.5.0

func (runtime *SessionRuntime) PendingMessages() QueueUpdateEvent

PendingMessages returns the queued steering and follow-up texts in queue order as copied slices — the pull-based counterpart of QueueUpdateEvent, so the TUI can render queue contents without racing delivery removal.

func (*SessionRuntime) Prompt added in v0.5.0

func (runtime *SessionRuntime) Prompt(ctx context.Context, input any, images ...*ai.ImageContent) error

func (*SessionRuntime) PromptAfterPreflight added in v0.5.0

func (runtime *SessionRuntime) PromptAfterPreflight(ctx context.Context, input any, images ...*ai.ImageContent) error

func (*SessionRuntime) PromptPreflight added in v0.5.0

func (runtime *SessionRuntime) PromptPreflight(ctx context.Context) error

func (*SessionRuntime) PromptSync added in v0.5.0

func (runtime *SessionRuntime) PromptSync(ctx context.Context, text string) error

PromptSync sends a prompt and blocks until the agent settles. It is a convenience wrapper combining Prompt + WaitForIdle.

func (*SessionRuntime) PromptWithOptions added in v0.5.0

func (runtime *SessionRuntime) PromptWithOptions(ctx context.Context, text string, options *PromptOptions) error

func (*SessionRuntime) ProviderAPIKey added in v0.5.0

func (runtime *SessionRuntime) ProviderAPIKey(ctx context.Context, provider ai.ProviderID) (string, error)

ProviderAPIKey resolves the API key the runtime would send for provider, the seam behind the TUI's Anthropic subscription-auth warning (upstream modelRuntime.getAuth(...)?.auth.apiKey in maybeWarnAboutAnthropicSubscriptionAuth). It lives here with the other login-flow seams owned by this work.

func (*SessionRuntime) QueueInteractive added in v0.5.0

func (runtime *SessionRuntime) QueueInteractive(ctx context.Context, text string, images []*ai.ImageContent, delivery extensions.DeliveryMode) error

QueueInteractive performs extension command/input handling and then queues the resolved message without consulting idle state. Interactive mode uses it after reserving an active prompt slot, closing the rapid-submit race before Agent.Prompt has installed its active run.

func (*SessionRuntime) RefreshCurrentModelFromRegistry added in v0.5.0

func (runtime *SessionRuntime) RefreshCurrentModelFromRegistry(registry extensions.ModelRegistry)

RefreshCurrentModelFromRegistry applies provider-dependent model projection changes after an in-place auth refresh without recording a model switch.

func (*SessionRuntime) RefreshModels added in v0.5.0

func (runtime *SessionRuntime) RefreshModels() error

RefreshModels mirrors upstream ModelRegistry.refresh() (model-registry.ts): since f8746813 a picker refresh re-reads models.json before rebuilding the provider snapshots, which orb's Reload already combines.

func (*SessionRuntime) RegisteredTool added in v0.5.0

func (runtime *SessionRuntime) RegisteredTool(name string) engine.AgentTool

RegisteredTool returns the configured agent.AgentTool for name — built-in or extension-wrapped, active or not. Renderers type-assert built-ins for their render seams (tools.PlainTextRenderer) instead of duplicating definitions.

func (*SessionRuntime) Reload added in v0.5.0

func (runtime *SessionRuntime) Reload(ctx context.Context) error

Reload rebuilds the session's native extension instance from its registered factories, then emits the reload lifecycle on the fresh context.

func (*SessionRuntime) ResourceLoader added in v0.5.0

func (runtime *SessionRuntime) ResourceLoader() ResourceLoader

ResourceLoader returns the resource instance that owns this session's skills, prompts, and theme objects.

func (*SessionRuntime) ScopedModels added in v0.5.0

func (runtime *SessionRuntime) ScopedModels() []ScopedModel

func (*SessionRuntime) SendCustomMessage added in v0.5.0

func (runtime *SessionRuntime) SendCustomMessage(ctx context.Context, message CustomMessage, options *SendCustomMessageOptions) error

func (*SessionRuntime) SendUserMessage added in v0.5.0

func (runtime *SessionRuntime) SendUserMessage(ctx context.Context, content ai.UserContent, options *SendUserMessageOptions) error

func (*SessionRuntime) SetActiveToolsByName added in v0.5.0

func (runtime *SessionRuntime) SetActiveToolsByName(names []string) error

func (*SessionRuntime) SetAutoCompactionEnabled added in v0.5.0

func (runtime *SessionRuntime) SetAutoCompactionEnabled(enabled bool)

func (*SessionRuntime) SetAutoRetryEnabled added in v0.5.0

func (runtime *SessionRuntime) SetAutoRetryEnabled(enabled bool)

func (*SessionRuntime) SetAutocompleteMaxVisible added in v0.5.0

func (runtime *SessionRuntime) SetAutocompleteMaxVisible(visible int)

func (*SessionRuntime) SetBlockImages added in v0.5.0

func (runtime *SessionRuntime) SetBlockImages(blocked bool)

func (*SessionRuntime) SetClearOnShrink added in v0.5.0

func (runtime *SessionRuntime) SetClearOnShrink(enabled bool)

func (*SessionRuntime) SetDefaultProjectTrust added in v0.5.0

func (runtime *SessionRuntime) SetDefaultProjectTrust(value string)

func (*SessionRuntime) SetDoubleEscapeAction added in v0.5.0

func (runtime *SessionRuntime) SetDoubleEscapeAction(action string)

func (*SessionRuntime) SetEditorPaddingX added in v0.5.0

func (runtime *SessionRuntime) SetEditorPaddingX(padding int)

func (*SessionRuntime) SetEnableSkillCommands added in v0.5.0

func (runtime *SessionRuntime) SetEnableSkillCommands(enabled bool)

func (*SessionRuntime) SetEnabledModels added in v0.5.0

func (runtime *SessionRuntime) SetEnabledModels(models []string)

func (*SessionRuntime) SetExtensionShutdownHandler added in v0.5.0

func (runtime *SessionRuntime) SetExtensionShutdownHandler(handler func())

SetExtensionShutdownHandler installs the mode-specific behavior for an extension's ctx.shutdown(). Upstream leaves it unset outside interactive and RPC, where shutdown is a no-op.

func (*SessionRuntime) SetFollowUpMode added in v0.5.0

func (runtime *SessionRuntime) SetFollowUpMode(mode engine.QueueMode)

func (*SessionRuntime) SetHTTPIdleTimeoutMS added in v0.5.0

func (runtime *SessionRuntime) SetHTTPIdleTimeoutMS(timeoutMS int64)

func (*SessionRuntime) SetHideThinkingBlock added in v0.5.0

func (runtime *SessionRuntime) SetHideThinkingBlock(hidden bool)

func (*SessionRuntime) SetImageAutoResize added in v0.5.0

func (runtime *SessionRuntime) SetImageAutoResize(enabled bool)

func (*SessionRuntime) SetImageWidthCells added in v0.5.0

func (runtime *SessionRuntime) SetImageWidthCells(width int)

func (*SessionRuntime) SetMermaidRenderingMode added in v0.5.0

func (runtime *SessionRuntime) SetMermaidRenderingMode(mode string)

func (*SessionRuntime) SetModel added in v0.5.0

func (runtime *SessionRuntime) SetModel(ctx context.Context, model ai.Model) error

func (*SessionRuntime) SetModelWithOptions added in v0.6.0

func (runtime *SessionRuntime) SetModelWithOptions(ctx context.Context, model ai.Model, options ModelMutationOptions) error

func (*SessionRuntime) SetOutputPad added in v0.5.0

func (runtime *SessionRuntime) SetOutputPad(padding int)

func (*SessionRuntime) SetQuietStartup added in v0.5.0

func (runtime *SessionRuntime) SetQuietStartup(enabled bool)

func (*SessionRuntime) SetScopedModels added in v0.5.0

func (runtime *SessionRuntime) SetScopedModels(models []ScopedModel)

func (*SessionRuntime) SetSessionName added in v0.5.0

func (runtime *SessionRuntime) SetSessionName(name string) error

func (*SessionRuntime) SetShowCacheMissNotices added in v0.5.0

func (runtime *SessionRuntime) SetShowCacheMissNotices(show bool)

func (*SessionRuntime) SetShowHardwareCursor added in v0.5.0

func (runtime *SessionRuntime) SetShowHardwareCursor(enabled bool)

func (*SessionRuntime) SetShowImages added in v0.5.0

func (runtime *SessionRuntime) SetShowImages(show bool)

func (*SessionRuntime) SetShowTerminalProgress added in v0.5.0

func (runtime *SessionRuntime) SetShowTerminalProgress(enabled bool)

func (*SessionRuntime) SetSteeringMode added in v0.5.0

func (runtime *SessionRuntime) SetSteeringMode(mode engine.QueueMode)

func (*SessionRuntime) SetTheme added in v0.5.0

func (runtime *SessionRuntime) SetTheme(name string) error

func (*SessionRuntime) SetThinkingLevel added in v0.5.0

func (runtime *SessionRuntime) SetThinkingLevel(level ai.ModelThinkingLevel) error

func (*SessionRuntime) SetThinkingLevelWithOptions added in v0.6.0

func (runtime *SessionRuntime) SetThinkingLevelWithOptions(level ai.ModelThinkingLevel, options ModelMutationOptions) error

func (*SessionRuntime) SetTransport added in v0.5.0

func (runtime *SessionRuntime) SetTransport(transport ai.Transport)

func (*SessionRuntime) SetTreeFilterMode added in v0.5.0

func (runtime *SessionRuntime) SetTreeFilterMode(value string)

func (*SessionRuntime) ShutdownExtensions added in v0.5.0

func (runtime *SessionRuntime) ShutdownExtensions(reason extensions.SessionShutdownReason, target *string)

func (*SessionRuntime) StartExtensions added in v0.5.0

func (runtime *SessionRuntime) StartExtensions()

StartExtensions activates a deferred session after the TUI has attached its UI implementation and event subscription.

func (*SessionRuntime) State added in v0.5.0

func (runtime *SessionRuntime) State() engine.AgentState

func (*SessionRuntime) Steer added in v0.5.0

func (runtime *SessionRuntime) Steer(text string) error

func (*SessionRuntime) SteerImages added in v0.5.0

func (runtime *SessionRuntime) SteerImages(text string, images []*ai.ImageContent) error

func (*SessionRuntime) SteeringMode added in v0.5.0

func (runtime *SessionRuntime) SteeringMode() engine.QueueMode

func (*SessionRuntime) String added in v0.5.0

func (runtime *SessionRuntime) String() string

func (*SessionRuntime) SubmitInteractive added in v0.5.0

func (runtime *SessionRuntime) SubmitInteractive(ctx context.Context, text string, images []*ai.ImageContent, delivery extensions.DeliveryMode) error

SubmitInteractive matches the interactive-mode delivery contract: an idle submission starts a turn, while a submission during streaming is queued as steer or follow-up without waiting for the active turn.

func (*SessionRuntime) Subscribe added in v0.5.0

func (runtime *SessionRuntime) Subscribe(listener func(any)) func()

func (*SessionRuntime) SubscribeChan added in v0.5.0

func (runtime *SessionRuntime) SubscribeChan(bufferSize int) (<-chan any, func())

SubscribeChan returns a buffered channel of session events and a cancel function. Events are the same types delivered to [AgentSession.Subscribe] callbacks: engine.AgentEvent variants and session-level event structs (AgentSettledEvent, QueueUpdateEvent, etc.).

Delivery is ordered and lossless while the subscription is active. The channel is closed promptly when cancel is called; events still queued at cancellation are discarded so cancellation never waits for a consumer. SessionRuntime.Dispose cancels every live subscription, so a caller that never cancels leaks nothing past the session it belongs to.

func (*SessionRuntime) SyncMessagesFromSession added in v0.5.0

func (runtime *SessionRuntime) SyncMessagesFromSession()

SyncMessagesFromSession reloads agent messages after a host-side setup callback mutates a replacement session.

func (*SessionRuntime) WaitForIdle added in v0.5.0

func (runtime *SessionRuntime) WaitForIdle(ctx context.Context) error

func (*SessionRuntime) WarnAnthropicExtraUsage added in v0.5.0

func (runtime *SessionRuntime) WarnAnthropicExtraUsage() bool

WarnAnthropicExtraUsage reads the warnings.anthropicExtraUsage settings gate for the Anthropic subscription-auth warning (upstream settingsManager.getWarnings().anthropicExtraUsage; default true).

type SessionRuntimeConfig added in v0.5.0

type SessionRuntimeConfig struct {
	Agent                  *engine.Agent
	SessionManager         *sessionstore.SessionManager
	Settings               *config.SettingsManager
	StreamFn               engine.StreamFn
	GetAPIKey              engine.GetAPIKeyFunc
	GetRequestAuth         engine.GetRequestAuthFunc
	GetModelHeaders        engine.GetModelHeadersFunc
	AvailableModels        func() []ai.Model
	ScopedModels           []ScopedModel
	Complete               harness.CompleteFunc
	Sleep                  func(context.Context, time.Duration) error
	Clock                  func() int64
	SlashResolver          *SlashResolver
	ExtensionRegistry      *extensions.Registry
	ExtensionMode          extensions.Mode
	ExtensionUI            extensions.UI
	ExtensionErrorHandler  func(extensions.ExtensionError)
	ModelRegistry          extensions.ModelRegistry
	RegisterProvider       func(extensions.Provider) error
	RegisterProviderConfig func(string, extensions.ProviderConfig) error
	UnregisterProvider     func(string) error
	BaseTools              []engine.AgentTool
	InitialActiveToolNames []string
	AllowedToolNames       *[]string
	ExcludedToolNames      []string
	RebuildBaseTools       func() ([]engine.AgentTool, error)
	SystemPromptOptions    *SystemPromptOptions
	BuiltinToolPrompts     map[string]ToolPromptContribution
	ResourceLoader         ResourceLoader
	SessionStartEvent      *extensions.SessionStartEvent
	DeferExtensionStart    bool
	SessionStart           *extensions.SessionStartEvent
	DeferSessionStart      bool
}

type SessionStats added in v0.5.0

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            SessionTokenTotals    `json:"tokens"`
	Cost              float64               `json:"cost"`
	ContextUsage      *harness.ContextUsage `json:"contextUsage,omitempty"`
}

type SessionTokenTotals added in v0.5.0

type SessionTokenTotals struct {
	Input      int64 `json:"input"`
	Output     int64 `json:"output"`
	CacheRead  int64 `json:"cacheRead"`
	CacheWrite int64 `json:"cacheWrite"`
	Total      int64 `json:"total"`
}

type Skill added in v0.5.0

type Skill struct {
	Name                   string
	Description            string
	Content                string
	FilePath               string
	BaseDir                string
	AllowedTools           string
	SourceInfo             SourceInfo
	DisableModelInvocation bool
}

Skill is the progressively-disclosed metadata for one Agent Skills file.

type SlashCommandInfo added in v0.5.0

type SlashCommandInfo struct {
	Name        string             `json:"name"`
	Description string             `json:"description,omitempty"`
	Source      SlashCommandSource `json:"source"`
	SourceInfo  SourceInfo         `json:"sourceInfo"`
}

type SlashCommandSource added in v0.5.0

type SlashCommandSource string
const (
	SlashCommandExtension SlashCommandSource = "extension"
	SlashCommandPrompt    SlashCommandSource = "prompt"
	SlashCommandSkill     SlashCommandSource = "skill"
)

type SlashResolver added in v0.5.0

type SlashResolver struct {
	Skills            []Skill
	PromptTemplates   []PromptTemplate
	ExtensionCommands []SlashCommandInfo
	ExecuteExtension  func(name, args string) (bool, error)
	InterceptInput    func(text string) (InputResult, error)
	OnError           func(error)
}

SlashResolver preserves the extension, input, skill, then template resolution order.

func (*SlashResolver) Commands added in v0.5.0

func (resolver *SlashResolver) Commands(_ bool) []SlashCommandInfo

Commands returns the core/RPC command-list order: extension, prompt, then skill. enableSkillCommands is an interactive autocomplete setting and does not hide commands from the session API.

func (*SlashResolver) Expand added in v0.5.0

func (resolver *SlashResolver) Expand(text string) string

Expand applies skill expansion before prompt-template expansion.

func (*SlashResolver) ExpandQueued added in v0.5.0

func (resolver *SlashResolver) ExpandQueued(text string) (string, error)

ExpandQueued rejects extension commands because their handlers must run synchronously through Prompt.

func (*SlashResolver) ResolvePrompt added in v0.5.0

func (resolver *SlashResolver) ResolvePrompt(text string) (string, bool)

ResolvePrompt applies every prompt-stage resolver and reports whether an extension consumed input.

type SourceInfo added in v0.5.0

type SourceInfo struct {
	Path    string `json:"path"`
	Source  string `json:"source"`
	Scope   string `json:"scope"`
	Origin  string `json:"origin"`
	BaseDir string `json:"baseDir,omitempty"`
}

SourceInfo identifies where a discovered slash-command resource came from.

type SummarizationRetryAttemptStartEvent added in v0.5.0

type SummarizationRetryAttemptStartEvent struct {
	Source string `json:"source"`
	Reason string `json:"reason,omitempty"`
}

type SummarizationRetryFinishedEvent added in v0.5.0

type SummarizationRetryFinishedEvent struct{}

type SummarizationRetryScheduledEvent added in v0.5.0

type SummarizationRetryScheduledEvent struct {
	Attempt      int    `json:"attempt"`
	MaxAttempts  int    `json:"maxAttempts"`
	DelayMS      int64  `json:"delayMs"`
	ErrorMessage string `json:"errorMessage"`
}

type SystemPromptOptions added in v0.5.0

type SystemPromptOptions struct {
	CustomPrompt       *string
	SelectedTools      []string
	ToolSnippets       map[string]string
	PromptGuidelines   []string
	AppendSystemPrompt *string
	CWD                string
	ContextFiles       []ContextFile
	Skills             []Skill
	PackageDir         string
}

SystemPromptOptions contains the already-resolved inputs to the upstream prompt builder. Nil SelectedTools means the upstream default tool set; a non-nil empty slice means no tools.

type ThinkingLevelChangedEvent added in v0.5.0

type ThinkingLevelChangedEvent struct {
	Level ai.ModelThinkingLevel `json:"level"`
}

type ToolPromptContribution added in v0.5.0

type ToolPromptContribution struct {
	Snippet    string
	Guidelines []string
}

ToolPromptContribution replaces one built-in tool's system-prompt contribution for a session. A present zero value suppresses the tool's contribution entirely — upstream's SDK-created coding tools (createCodingTools) drop every contribution except bash's, whose snippet and guideline wording differ from the interactive defaults; the extension session bridge mirrors that surface through these overrides.

type UsageCostBreakdownEntry added in v0.5.0

type UsageCostBreakdownEntry struct {
	Key    string  `json:"key"`
	Cost   float64 `json:"cost"`
	Tokens int64   `json:"tokens"`
}

func GetUsageCostBreakdown added in v0.5.0

func GetUsageCostBreakdown(entries []sessionstore.SessionEntry) []UsageCostBreakdownEntry

GetUsageCostBreakdown groups model-attributed usage and auxiliary tool/summary usage.

Directories

Path Synopsis
Package assembly enumerates the compiled composition of the orb product — compiled extensions, first-party plugins, and MCP — as ordered rows with stable ids, resolves their enablement from settings, and loads the result.
Package assembly enumerates the compiled composition of the orb product — compiled extensions, first-party plugins, and MCP — as ordered rows with stable ids, resolves their enablement from settings, and loads the result.
examples
01_minimal command
Minimal SDK usage with all defaults.
Minimal SDK usage with all defaults.
02_custom_model command
Custom model selection and thinking level.
Custom model selection and thinking level.
03_custom_prompt command
Custom system prompt replacement and extension through DefaultResourceLoader.
Custom system prompt replacement and extension through DefaultResourceLoader.
04_skills command
Skills configuration through DefaultResourceLoader discovery and overrides.
Skills configuration through DefaultResourceLoader discovery and overrides.
05_tools command
Tools configuration: tool allowlists and denylists.
Tools configuration: tool allowlists and denylists.
06_extensions command
Extensions configuration through DefaultResourceLoader inline factories.
Extensions configuration through DefaultResourceLoader inline factories.
07_context_files command
Context files discovered and extended through DefaultResourceLoader.
Context files discovered and extended through DefaultResourceLoader.
08_prompt_templates command
Prompt templates discovered and extended through DefaultResourceLoader.
Prompt templates discovered and extended through DefaultResourceLoader.
09_api_keys command
API key and OAuth configuration through ModelRegistry and runtime callbacks.
API key and OAuth configuration through ModelRegistry and runtime callbacks.
10_settings command
Settings configuration through SettingsManager.
Settings configuration through SettingsManager.
11_sessions command
Session management: in-memory, persistent, continue, list, and open.
Session management: in-memory, persistent, continue, list, and open.
12_full_control command
Full control: explicit model, settings, session, ResourceLoader, and tools.
Full control: explicit model, settings, session, ResourceLoader, and tools.
13_session_runtime command
Session runtime demonstrates recreating cwd-bound services when the active AgentSession is replaced and rebinding session-local host state.
Session runtime demonstrates recreating cwd-bound services when the active AgentSession is replaced and rebinding session-local host state.
Package extensions provides the Go-native extension registry, API surface, and ordered event runner used by the coding agent.
Package extensions provides the Go-native extension registry, API surface, and ordered event runner used by the coding agent.
host
Package host implements orb's original out-of-process JavaScript extension host protocol and lifecycle manager.
Package host implements orb's original out-of-process JavaScript extension host protocol and lifecycle manager.
Package mcp implements orb's bundled, settings-driven MCP extension.
Package mcp implements orb's bundled, settings-driven MCP extension.
Package modes contains coding-agent run-mode orchestration.
Package modes contains coding-agent run-mode orchestration.
Package plugins contains orb's default-off first-party extensions.
Package plugins contains orb's default-off first-party extensions.
Package session stores coding-agent conversations as pi-compatible JSONL trees.
Package session stores coding-agent conversations as pi-compatible JSONL trees.

Jump to

Keyboard shortcuts

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