coding

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 26 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 }

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

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.

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 coding/pigversion/pigversion.go, then run the upgrade workflow in piglets/porter/skills/pig-porter/SKILL.md.

Index

Constants

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(...)
model, _ := coding.BuildModel("github-copilot/gpt-4o-mini", svcs)
rt, _ := coding.NewRuntime(coding.RuntimeOptions{Services: svcs})
sess, _ := rt.New(coding.SessionStartOptions{Model: model})

func BuildUserContent

func BuildUserContent(text string, images []ai.ImageContent) []ai.UserContentBlock

BuildUserContent constructs the upstream user-content block list: optional leading text block plus 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 BashResult

type BashResult struct {
	Output         string `json:"output"`
	ExitCode       int    `json:"exitCode"`
	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 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 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) 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 NewModelRuntime

func NewModelRuntime(services *Services) (*ModelRuntime, error)

NewModelRuntime constructs a runtime backed by services model configuration and credentials.

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) 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) 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 and auth failures terminate the returned stream with ErrorEvent.

func (*ModelRuntime) StreamSimple

func (runtime *ModelRuntime) StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream

StreamSimple uses the same normalization and request preparation path as Stream. Go providers expose one typed Stream contract, so provider-neutral options lower directly into ai.StreamOptions.

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 Runtime

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

Runtime is the top-level SDK factory: it owns a Services container, an extension runner, and produces *Session values for fresh / resumed / cloned sessions.

Legacy ExtensionRunner removed: only inproc.Runner remains.

func NewRuntime

func NewRuntime(opts RuntimeOptions) (*Runtime, error)

NewRuntime constructs a Runtime.

func (*Runtime) Close

func (rt *Runtime) Close() error

Close releases Runtime-level resources.

func (*Runtime) Continue

func (rt *Runtime) Continue(opts SessionStartOptions) (*Session, error)

Continue resumes the most-recent Session.

func (*Runtime) ExtensionContext

func (rt *Runtime) ExtensionContext() *icodingagent.ExtensionContext

ExtensionContext returns the shared extension context.

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

func (rt *Runtime) SetBeforeSessionInvalidate(fn func())

SetBeforeSessionInvalidate installs a synchronous teardown hook that runs before the runner is invalidated.

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

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

func (*Services) CWD

func (s *Services) CWD() string

CWD returns the working directory this Services container was constructed with.

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 → os.Getwd().
	CWD string

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

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. On success the session has either created a fresh JSONL (ResumePath empty) or loaded an existing one (ResumePath set).

Errors:

  • svcs is nil → ErrNoServices
  • opts.Model is nil → session is created without an initial model_change/thinking_level_change event; the caller must call SetModel later (typical for interactive mode launched without `--model` and no detectable credentials, mirroring upstream pi's behavior).
  • 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) 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. Returns the new Session; the caller should Close the new session when done. The original session is unchanged.

Per row 3.1 contract: clone writes a separate file with parentSession metadata pointing at the source. Linear path only: orphan branches are dropped.

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

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

Close releases the session's resources. After Close, further calls to Send return an error. Calling Close more than once is safe and returns nil on subsequent calls.

Close does NOT delete the on-disk JSONL: sessions persist across process restarts and are reopened via Runtime.Open or Runtime.Resume. EmitSessionStart dispatches a session_start event to extension handlers. reason is one of "startup" | "reload" | "new" | "resume" | "fork".

Upstream emits this inside AgentSession.bindExtensions (agent-session.ts:2092), which every mode calls (print-mode.ts:73, rpc-mode.ts:318, interactive-mode.ts:1544). Pig's interactive path fires it via codingagent.emitSessionStart; the print/rpc/json entry points call this method so extensions receive the event in all modes, not only interactive. Without it, extensions that initialize on session_start (e.g. set up output dirs, register session state) are silently skipped outside the TUI.

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

func (*Session) ExecuteBashWithOperations

func (s *Session) ExecuteBashWithOperations(ctx context.Context, command string, excludeFromContext bool, onChunk func(string), operations extension.BashOperations) (BashResult, error)

ExecuteBashWithOperations executes Bash through operations, such as those a user_bash handler returned, reporting each output chunk. nil operations run the command locally. Mirrors upstream executeBash's options.operations.

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.

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) 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(text string, images []ai.ImageContent)

FollowUp queues a user message for delivery after the active turn settles.

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

func (s *Session) GetSessionStats() SessionStats

GetSessionStats returns aggregate stats for this session. Mirrors upstream getSessionStats (agent-session.ts:2887-2935).

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

func (s *Session) RecordBashResult(command string, result BashResult, excludeFromContext bool)

RecordBashResult records a bash result an extension produced itself (a user_bash result override) exactly as a locally executed command's result. Mirrors upstream AgentSession.recordBashResult.

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

func (s *Session) ReplaceInner(sess *icodingagent.Session)

ReplaceInner aborts work owned by the old Session, then installs the new Session state.

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 cancels the active run, retry wait, compaction, and branch summary without waiting. Extensions abort this way: upstream's ctx.abort() does not await the run it stops.

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.

Unlike SendContent, the Session lock is held only for post-run handling, so the interactive owner loop can still refresh or replace the Session while a low-level run streams. Before each continuation and before returning, it 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) 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 is the structured-content variant of Send. It persists the full user content (text and/or images), then runs the agent loop.

func (*Session) SendContentWithPreflight

func (s *Session) SendContentWithPreflight(ctx context.Context, content []ai.UserContentBlock, preflight func()) ([]agent.AgentMessage, error)

SendContentWithPreflight calls preflight after prompt validation and extension input processing complete, immediately before the agent run starts. The run is active (IsStreaming) from then until agent_settled, and Abort cancels it. Prompts extensions send while agent_settled is dispatched run before this returns, as upstream prompt() awaits them.

func (*Session) SendUserMessage

func (s *Session) SendUserMessage(content any, deliverAs extension.DeliverAs) error

SendUserMessage delivers an extension's user message (upstream sendUserMessage → prompt with source "extension" and no template expansion). content is a string or an array of text and image blocks. It returns only content and option errors; like upstream, the prompt itself runs asynchronously and its failures are reported as extension errors.

func (*Session) Services

func (s *Session) Services() *Services

Services returns the parent Services container.

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 the Session's tools named in names, in that order. Names the Session has no tool for are ignored. The change applies from the next provider request, which declares the new loadout, and the Session's default system prompt lists the active tools from the next prompt. 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) 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.

func (*Session) SetName

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

SetName persists a session name as a SessionInfoEntry on disk. The name surfaces in ListSessions / Runtime.ListSessions output and in the resume picker UI. Empty name removes the most recent name (silent no-op on filesystems where the entry doesn't exist).

func (*Session) SetSessionName

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

SetSessionName persists a Session name entry. An empty name clears the current name, as extension API calls can do in Pi. RPC and slash-command boundaries validate their own non-empty input before calling this method.

func (*Session) SetSteeringMode

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

SetSteeringMode updates the active queue and persists its drain mode.

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

func (s *Session) Steer(text string, images []ai.ImageContent)

Steer queues a user message for delivery before the next model call in the active turn.

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. A listener must not wait for a Session operation that synchronously emits another event; queue that work instead.

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) 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 the active tool list (defaults + caller-supplied, filtered by AllowedTools). Defensive copy; safe for callers to inspect or extend (extension won't affect the running agent).

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

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

WaitForIdle blocks until the session is idle, ctx ends, or the session closes (upstream waitForIdle).

type SessionContextUsage

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

type SessionInfo

type SessionInfo = icodingagent.SessionInfo

SessionInfo is the picker-display summary for a session JSONL. Re-exported alias from internal/codingagent.

type SessionOptions

type SessionOptions struct {
	// Model is the LLM model to use for this session. Required.
	Model *ai.Model

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

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

	// 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 = all built-in tools. Mirrors
	// upstream defaultActiveToolNames (sdk.ts:244): the CLI default is
	// [read, bash, edit, write]; grep/find/ls are registered but inactive
	// unless requested via --tools.
	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 disables event dispatch.
	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

	// 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 {
	// Model is the LLM the agent calls. Required.
	Model *ai.Model

	// SystemPrompt is the system prompt.
	SystemPrompt string

	// SystemPromptSections carries the caller-built structured prompt.
	SystemPromptSections ai.OrderedSections

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

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

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 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.
installresolver
Package installresolver is Pig's product-neutral seam for contributed package-source behavior.
Package installresolver is Pig's product-neutral seam for contributed package-source behavior.
pigsdk
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary.
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary.
source
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition.
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition.
Package hookconfig parses and validates command hook files shared by Package validation and the runtime hook bridge.
Package hookconfig parses and validates command hook files shared by Package validation and the runtime hook bridge.
Package packagecontent discovers resources exposed by Pi packages and cross-harness plugin manifests.
Package packagecontent discovers resources exposed by Pi packages and cross-harness plugin manifests.
Package piglet provides piglet-based capability scoping for pig sessions.
Package piglet provides piglet-based capability scoping for pig sessions.
artifact
Package artifact defines executable Piglet component plans and artifact records.
Package artifact defines executable Piglet component plans and artifact records.
release
Package release verifies and installs signed Piglet Binary releases.
Package release verifies and installs signed Piglet Binary releases.
signature
Package signature signs and verifies Piglet Binaries.
Package signature signs and verifies Piglet Binaries.
Package pigletbuild validates Piglet closure and builds source or binary Piglet artifacts.
Package pigletbuild validates Piglet closure and builds source or binary Piglet artifacts.
binarypiglet
Package binarypiglet holds the Piglet and resolution record embedded in a Piglet Binary.
Package binarypiglet holds the Piglet and resolution record embedded in a Piglet Binary.
Package pigversion provides PiG and upstream Pi version pins to packages that cannot import coding.
Package pigversion provides PiG and upstream Pi version pins to packages that cannot import coding.
Package rpcclient is a Go client for `pig --mode rpc`: it spawns the agent in RPC mode and provides a typed API for all operations.
Package rpcclient is a Go client for `pig --mode rpc`: it spawns the agent in RPC mode and provides a typed API for all operations.
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