run

package
v0.0.356 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PlatformConsole  = "console"
	PlatformWeb      = "web"
	PlatformTelegram = "telegram"
	PlatformJob      = "jobs"
	PlatformChat     = "chat"
	PlatformExec     = "exec"
)
View Source
const DefaultRunnerCleanupTimeout = 5 * time.Second

DefaultRunnerCleanupTimeout bounds how long EventPipe adapters wait for a cancelled Runner.Run to finish its own cleanup before detaching. The runner goroutine may still be stuck, but callers must not let that wedge UI/session goroutines that already cancelled their stream context.

Variables

This section is empty.

Functions

func WaitForRunnerDone added in v0.0.322

func WaitForRunnerDone(ctx context.Context, done <-chan struct{}, timeout time.Duration) bool

WaitForRunnerDone waits for Runner.Run to return after its stream context has been cancelled. It deliberately starts a fresh timeout and ignores ctx.Done(), because callers commonly pass a run context they have just cancelled and still need to allow a small cleanup grace period.

Types

type ApprovalPrompter

type ApprovalPrompter interface {
	PromptApproval(target string, isWrite, isShell bool, workDir string) (tools.ApprovalResult, error)
}

ApprovalPrompter is an optional EventSink capability. Interactive platforms implement it; headless platforms such as jobs intentionally do not.

type AskUserPrompter

type AskUserPrompter interface {
	AskUser(ctx context.Context, questions []tools.AskUserQuestion) ([]tools.AskUserAnswer, error)
}

AskUserPrompter is an optional EventSink capability for the ask_user tool.

type ChildRunEventCallback added in v0.0.337

type ChildRunEventCallback func(runID string, event tools.SubagentEvent)

ChildRunEventCallback receives structured child progress keyed by the direct run ID rather than a fabricated parent tool-call ID.

type ChildRunKind added in v0.0.337

type ChildRunKind string

ChildRunKind identifies why a fresh child runtime was started.

const (
	ChildRunSpawnAgent    ChildRunKind = "spawn_agent"
	ChildRunIsolatedSkill ChildRunKind = "isolated_skill"
)

type ChildRunRequest added in v0.0.337

type ChildRunRequest struct {
	Kind            ChildRunKind
	RunID           string
	ChildSessionID  string
	AgentName       string
	Prompt          string
	ModelOverride   string
	ParentSessionID string
	BaseDir         string
	Depth           int
	Skill           *SkillRunMetadata
}

ChildRunRequest is the shared child-runtime contract used by spawn_agent and direct isolated skill invocation.

type ChildRunResult added in v0.0.337

type ChildRunResult struct {
	RunID          string
	ChildSessionID string
	Output         string
	Provider       string
	Model          string
	StartedAt      time.Time
	CompletedAt    time.Time
}

ChildRunResult identifies the durable child session and collected output.

type ChildRunner added in v0.0.337

type ChildRunner interface {
	RunChild(ctx context.Context, request ChildRunRequest, callback ChildRunEventCallback) (ChildRunResult, error)
}

ChildRunner executes a fresh child runtime synchronously. Callers normally invoke it from their own goroutine/tea.Cmd and cancel through ctx.

type ErrorEventSink

type ErrorEventSink interface {
	EventWithError(ev llm.Event) error
}

ErrorEventSink is an optional EventSink capability for sinks that need to propagate consumer/backpressure failures to stop the producer.

type EventPipe

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

EventPipe adapts a Runner EventSink into an llm.Stream. It is useful for platforms that already consume streams through existing stream adapters while the shared runner owns execution.

func NewEventPipe

func NewEventPipe(ctx context.Context, buffer int) *EventPipe

NewEventPipe creates an EventPipe with the requested event buffer size.

func (*EventPipe) Close

func (p *EventPipe) Close() error

Close implements llm.Stream. Closing is producer-owned via CloseWithError, so this is intentionally a no-op for stream adapters.

func (*EventPipe) CloseWithError

func (p *EventPipe) CloseWithError(err error)

CloseWithError marks the producer complete. It must be called exactly once by the producer after Runner.Run returns.

func (*EventPipe) Event

func (p *EventPipe) Event(ev llm.Event)

Event implements EventSink. It drops the event only when the pipe context has been cancelled.

func (*EventPipe) EventWithError

func (p *EventPipe) EventWithError(ev llm.Event) error

EventWithError implements ErrorEventSink so runner producers can stop when a consumer has cancelled the pipe context.

func (*EventPipe) Events

func (p *EventPipe) Events() <-chan llm.Event

Events exposes the raw event channel for consumers that already multiplex on channels. Prefer Recv when an llm.Stream is accepted.

func (*EventPipe) Recv

func (p *EventPipe) Recv() (llm.Event, error)

Recv implements llm.Stream.

type EventSink

type EventSink interface {
	Event(ev llm.Event)
}

EventSink receives the raw llm.Event stream for a run. Implementations should do rendering/translation only; they should not own runner wiring.

type GuardianEventSink

type GuardianEventSink interface {
	GuardianEvent(event tools.GuardianEvent)
}

GuardianEventSink is an optional EventSink capability for guardian review notices emitted by auto-approval mode.

type ProgressiveOptions

type ProgressiveOptions struct {
	Timeout      time.Duration
	StopWhen     string
	ContinueWith string
}

ProgressiveOptions describes an iterative/progressive run. A nil *ProgressiveOptions on Request means a normal single execution.

type ProgressiveResult

type ProgressiveResult struct {
	ExitReason    string         `json:"exit_reason"`
	Finalized     bool           `json:"finalized"`
	SessionID     string         `json:"session_id,omitempty"`
	Sequence      int            `json:"sequence,omitempty"`
	Reason        string         `json:"reason,omitempty"`
	Message       string         `json:"message,omitempty"`
	Progress      map[string]any `json:"progress,omitempty"`
	FinalResponse string         `json:"final_response,omitempty"`
	FallbackText  string         `json:"fallback_text,omitempty"`
}

ProgressiveResult is the platform-neutral form of the progressive execution summary produced by the command-layer runner.

type Request

type Request struct {
	Platform string

	AgentName string
	Prompt    string
	Messages  []llm.Message

	// Engine/ProviderInstance let stateful callers (chat/telegram) run through
	// the shared runner while reusing their session-scoped engine/provider/MCP
	// resources instead of rebuilding them every turn. When supplied, the runner
	// treats them as borrowed and does not close provider-owned resources.
	Engine           *llm.Engine
	ProviderInstance llm.Provider

	SessionID    string
	SessionName  string
	Resume       bool
	Persist      bool
	DeferSession bool
	// DisableRuntimePersistence keeps any configured store available for tool
	// wiring (notably spawn_agent) while preventing the shared runtime from
	// writing session rows. Platforms that already own persistence can use their
	// callbacks instead.
	DisableRuntimePersistence bool
	Stateful                  bool
	ReplaceHistory            bool

	Provider string
	Model    string
	Cwd      string

	Tools      string
	ReadDirs   []string
	WriteDirs  []string
	ShellAllow []string
	MCP        string
	Skills     string

	SystemMessage               string
	MaxTurns                    int
	MaxTurnsSet                 bool
	MaxOutputTokens             int
	ServiceTier                 string
	ServiceTierSet              bool
	ContextEstimateTotalTokens  int
	ContextEstimateMessageCount int
	Search                      *bool
	NoSearch                    bool

	Yolo     bool
	Auto     bool
	Debug    bool
	DebugRaw bool

	ForceExternalSearch     *bool
	DisableExternalWebFetch bool
	ExtraTools              []llm.ToolSpec
	ForceToolName           string
	LastTurnForceToolName   string
	IncludeConfiguredTools  *bool

	OnAssistantSnapshot    llm.AssistantSnapshotCallback
	OnResponseCompleted    llm.ResponseCompletedCallback
	OnTurnCompleted        llm.TurnCompletedCallback
	OnCompaction           llm.CompactionCallback
	OnSyntheticUserMessage func(context.Context, llm.Message) error
	OnEngineReady          func(*llm.Engine)
	OnEngineDone           func(*llm.Engine)

	Progressive *ProgressiveOptions

	// Sub-agent/session-linking options used by spawn_agent migrations.
	ParentSessionID          string
	IsSubagent               bool
	Depth                    int
	ApprovalRole             string
	ApprovalTranscriptPrefix []llm.Message

	// ChildSkill configures an already-resolved direct skill on a fresh child
	// engine. It is never interpreted as a request for model-driven activation.
	ChildSkill *SkillRunMetadata
}

Request is a single LLM execution request. It intentionally carries execution semantics (agent, prompt/history, settings overrides, persistence and runtime capabilities) but not presentation details; presentation belongs to EventSink implementations owned by each platform.

type Result

type Result struct {
	SessionID string
	Provider  string
	Model     string
	Response  string
	Thinking  string

	Turns        int
	InputTokens  int
	OutputTokens int

	ExitReason  string
	Progressive *ProgressiveResult

	// Engine is exposed for legacy command UIs that provide post-run affordances
	// (for example exec's command help). New platform code should prefer events
	// and Result fields over reaching into the engine.
	Engine           *llm.Engine
	ProviderInstance llm.Provider
}

Result summarizes execution independently of platform rendering.

type Runner

type Runner interface {
	Run(ctx context.Context, req Request, sink EventSink) (Result, error)
}

Runner executes one Request and streams events to a sink.

type SkillRunMetadata added in v0.0.337

type SkillRunMetadata struct {
	Name                string
	Source              string
	SourcePath          string
	RawArguments        string
	AllowedTools        []string
	AllowedToolsPresent bool
	ToolDefs            []skills.SkillToolDef
	Resources           []string
}

SkillRunMetadata carries the resolved activation into a child engine without requiring the child model to rediscover or activate the skill.

Jump to

Keyboard shortcuts

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