interpreter

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: GPL-3.0 Imports: 34 Imported by: 0

Documentation

Overview

Package interpreter provides native tool implementations that can be shared between the SDK (gsh.tools) and the REPL agent.

Index

Constants

View Source
const (
	EventAgentStart          = "agent.start"
	EventAgentEnd            = "agent.end"
	EventAgentIterationStart = "agent.iteration.start"
	EventAgentIterationEnd   = "agent.iteration.end"
	EventAgentChunk          = "agent.chunk"
	EventAgentToolPending    = "agent.tool.pending"
	EventAgentToolStart      = "agent.tool.start"
	EventAgentToolEnd        = "agent.tool.end"
)

Agent lifecycle event names

View Source
const (
	EventReplReady         = "repl.ready"
	EventReplExit          = "repl.exit"
	EventReplPrompt        = "repl.prompt"
	EventReplCommandBefore = "repl.command.before"
	EventReplCommandAfter  = "repl.command.after"
	EventReplPredict       = "repl.predict"
)

REPL event names

View Source
const DefaultExecTimeout = 60 * time.Second

DefaultExecTimeout is the default timeout for command execution.

View Source
const DefaultMaxIterations = 100

DefaultMaxIterations is the default maximum number of tool call iterations if not specified in the agent config.

Variables

This section is empty.

Functions

func BuildGrepCommand

func BuildGrepCommand(backend GrepBackend, pattern string) (string, []string, error)

BuildGrepCommand builds the appropriate grep command based on the backend and pattern.

func ExecuteNativeEditFileTool

func ExecuteNativeEditFileTool(ctx context.Context, args map[string]interface{}) (string, error)

ExecuteNativeEditFileTool performs a find-and-replace edit on a file.

func ExecuteNativeExecTool

func ExecuteNativeExecTool(ctx context.Context, args map[string]interface{}, liveOutput io.Writer) (string, error)

ExecuteNativeExecTool executes a shell command with PTY support. This is the shared implementation used by both gsh.tools.exec and the REPL agent. The working_directory must be provided in args and must be an absolute path.

func ExecuteNativeGrepTool

func ExecuteNativeGrepTool(ctx context.Context, args map[string]interface{}) (string, error)

ExecuteNativeGrepTool searches for a regex pattern in files.

func ExecuteNativeViewFileTool

func ExecuteNativeViewFileTool(ctx context.Context, args map[string]interface{}) (string, error)

ExecuteNativeViewFileTool reads a file and returns its content with line numbers.

func ExecuteViewFile

func ExecuteViewFile(ctx context.Context, filePath string, startLine, endLine int) (string, error)

ExecuteViewFile reads a file and returns its content with line numbers. Line numbers are 1-indexed and formatted as 5-digit prefixes (e.g., " 1:content"). If startLine and endLine are provided (1-indexed, inclusive), only that range is returned. If the output exceeds 100KB, lines from the middle are truncated and replaced with "(truncated)".

func ExtractPredictionResult added in v1.2.0

func ExtractPredictionResult(val Value) (string, error, bool)

ExtractPredictionResult extracts a prediction result from an event handler return value. Supported return formats:

  • string: treated as the prediction
  • object: { prediction: string, error?: string }

Returns prediction, error (if provided), and a boolean indicating whether a value was handled.

func GetSpinnerManager

func GetSpinnerManager() *render.SpinnerManager

GetSpinnerManager returns the global spinner manager (for testing)

func GrepBackendName

func GrepBackendName(backend GrepBackend) string

GrepBackendName returns a human-readable name for the backend.

func SetSpinnerManager

func SetSpinnerManager(manager *render.SpinnerManager)

SetSpinnerManager sets the global spinner manager (for testing)

func TruncateFromMiddle

func TruncateFromMiddle(lines []string, maxLen int) string

TruncateFromMiddle removes lines from the middle of the output to fit within maxLen, replacing them with a "(truncated)" marker.

func ValueToInterface

func ValueToInterface(val Value) interface{}

ValueToInterface converts a Value to interface{}. This is the canonical conversion function used throughout the interpreter.

Types

type ACPClientFactory added in v1.1.0

type ACPClientFactory func(config acp.ClientConfig) (*acp.Client, error)

ACPClientFactory is a function type for creating ACP clients. This can be overridden in tests to inject mock clients.

type ACPSessionMethodValue added in v1.1.0

type ACPSessionMethodValue struct {
	Name    string
	Session *ACPSessionValue
	Interp  *Interpreter
}

ACPSessionMethodValue represents a method bound to an ACPSessionValue instance

func (*ACPSessionMethodValue) Equals added in v1.1.0

func (m *ACPSessionMethodValue) Equals(other Value) bool

func (*ACPSessionMethodValue) IsTruthy added in v1.1.0

func (m *ACPSessionMethodValue) IsTruthy() bool

func (*ACPSessionMethodValue) String added in v1.1.0

func (m *ACPSessionMethodValue) String() string

func (*ACPSessionMethodValue) Type added in v1.1.0

func (m *ACPSessionMethodValue) Type() ValueType

type ACPSessionValue added in v1.1.0

type ACPSessionValue struct {
	// Agent is the ACP agent this session is bound to
	Agent *ACPValue

	// Messages tracks conversation history locally for property access.
	// This is a local copy - the external agent owns the authoritative state.
	Messages []ChatMessage

	// SessionID is the external agent's session identifier (set after initialization)
	SessionID string

	// Closed indicates if the session has been terminated
	Closed bool
}

ACPSessionValue represents an active session with an ACP agent. It tracks the conversation messages locally for property access, though the authoritative state is maintained by the external agent.

func (*ACPSessionValue) Close added in v1.1.0

func (s *ACPSessionValue) Close()

Close marks the session as closed. This is called when session.close() is invoked from gsh script.

func (*ACPSessionValue) Equals added in v1.1.0

func (s *ACPSessionValue) Equals(other Value) bool

func (*ACPSessionValue) GetProperty added in v1.1.0

func (s *ACPSessionValue) GetProperty(name string) Value

GetProperty returns a property of the ACP session. Mirrors ConversationValue's property interface for consistency.

func (*ACPSessionValue) IsTruthy added in v1.1.0

func (s *ACPSessionValue) IsTruthy() bool

func (*ACPSessionValue) String added in v1.1.0

func (s *ACPSessionValue) String() string

func (*ACPSessionValue) Type added in v1.1.0

func (s *ACPSessionValue) Type() ValueType

type ACPValue added in v1.1.0

type ACPValue struct {
	Name   string           // Agent name from declaration
	Config map[string]Value // Configuration (command, args, env, cwd, etc.)
}

ACPValue represents an ACP (Agent Client Protocol) agent configuration. Unlike AgentValue which has a local model and tools, ACPValue connects to an external agent process via the ACP protocol.

func (*ACPValue) Equals added in v1.1.0

func (a *ACPValue) Equals(other Value) bool

func (*ACPValue) GetProperty added in v1.1.0

func (a *ACPValue) GetProperty(name string) Value

GetProperty returns a property of the ACP agent configuration

func (*ACPValue) IsTruthy added in v1.1.0

func (a *ACPValue) IsTruthy() bool

func (*ACPValue) String added in v1.1.0

func (a *ACPValue) String() string

func (*ACPValue) Type added in v1.1.0

func (a *ACPValue) Type() ValueType

type AgentCallbacks

type AgentCallbacks struct {
	// OnIterationStart is called at the start of each agentic loop iteration.
	OnIterationStart func(iteration int)

	// OnChunk is called for each streaming content chunk.
	// Only called when Streaming is true.
	// Aligned with ACP's session/update message_chunk notifications.
	OnChunk func(content string)

	// OnToolPending is called when a tool call enters pending state (starts streaming from LLM).
	// At this point, we know the tool name but arguments may be incomplete/empty.
	// This allows showing a "pending" state to the user while arguments stream in.
	// The toolName is always available; partialArgs may be empty or partial.
	OnToolPending func(toolCallID string, toolName string)

	// OnToolCallStart is called before executing a tool.
	// The ToolCall contains the tool's initial state with Status = pending.
	// Aligned with ACP's session/update tool_call notifications.
	OnToolCallStart func(toolCall acp.ToolCall)

	// OnToolCallEnd is called after a tool completes.
	// The ToolCallUpdate contains the final status, result, and duration.
	// Aligned with ACP's session/update tool_call_update notifications.
	OnToolCallEnd func(toolCall acp.ToolCall, update acp.ToolCallUpdate)

	// OnResponse is called when a complete response is received (with usage stats).
	OnResponse func(response *ChatResponse)

	// OnComplete is called when the agent finishes.
	// The AgentResult contains the stop reason, token usage, and any error.
	// Aligned with ACP's session/prompt response with StopReason.
	OnComplete func(result acp.AgentResult)

	// Tools provides additional tools to be sent to the LLM.
	// These are merged with any tools defined in the agent's config.
	// This allows the REPL to provide built-in tools (exec, grep, etc.)
	// without modifying the agent's config.
	Tools []ChatTool

	// ToolExecutor overrides the default tool execution.
	// If nil, uses the interpreter's built-in tool resolution.
	// This allows the REPL to provide its own tool implementations (exec, grep, etc.)
	ToolExecutor func(ctx context.Context, toolName string, args map[string]interface{}) (string, error)

	// EventEmitter is called to emit SDK events (agent.start, agent.end, etc.).
	// If set, the interpreter will call this function to emit events.
	// The function receives the event name and a context object.
	// Handlers that want to produce output should print directly to stdout.
	// This allows the REPL to handle event emission through the SDK system.
	EventEmitter func(eventName string, ctx Value)
}

AgentCallbacks provides hooks for observing and customizing agent execution. All callbacks are optional - nil callbacks are simply not called. This allows the REPL to drive its UI without the interpreter knowing about rendering.

The callback types are aligned with the Agent Client Protocol (ACP) specification for standardized communication patterns. See: https://agentclientprotocol.com/

type AgentValue

type AgentValue struct {
	Name   string
	Config map[string]Value
}

AgentValue represents an agent configuration

func (*AgentValue) Equals

func (a *AgentValue) Equals(other Value) bool

func (*AgentValue) GetProperty added in v1.2.0

func (a *AgentValue) GetProperty(name string) Value

GetProperty returns a property of the agent. Supports "name" for the agent name, "metadata" for user-defined metadata, and any other config field.

func (*AgentValue) IsTruthy

func (a *AgentValue) IsTruthy() bool

func (*AgentValue) String

func (a *AgentValue) String() string

func (*AgentValue) Type

func (a *AgentValue) Type() ValueType

type ArrayMethodValue

type ArrayMethodValue struct {
	Name string
	Impl arrayMethodImpl
	Arr  *ArrayValue // The array instance this method is bound to
}

ArrayMethodValue wraps an array method that needs to be bound to an instance at call time

func (*ArrayMethodValue) Equals

func (a *ArrayMethodValue) Equals(other Value) bool

func (*ArrayMethodValue) IsTruthy

func (a *ArrayMethodValue) IsTruthy() bool

func (*ArrayMethodValue) String

func (a *ArrayMethodValue) String() string

func (*ArrayMethodValue) Type

func (a *ArrayMethodValue) Type() ValueType

type ArrayValue

type ArrayValue struct {
	Elements []Value
}

ArrayValue represents an array value

func (*ArrayValue) DeepCopy

func (a *ArrayValue) DeepCopy() *ArrayValue

DeepCopy creates a completely independent deep copy of the ArrayValue. Modifying the copy will not affect the original array.

func (*ArrayValue) Equals

func (a *ArrayValue) Equals(other Value) bool

func (*ArrayValue) IsTruthy

func (a *ArrayValue) IsTruthy() bool

func (*ArrayValue) String

func (a *ArrayValue) String() string

func (*ArrayValue) Type

func (a *ArrayValue) Type() ValueType

type BoolValue

type BoolValue struct {
	Value bool
}

BoolValue represents a boolean value

func (*BoolValue) Equals

func (b *BoolValue) Equals(other Value) bool

func (*BoolValue) IsTruthy

func (b *BoolValue) IsTruthy() bool

func (*BoolValue) String

func (b *BoolValue) String() string

func (*BoolValue) Type

func (b *BoolValue) Type() ValueType

type BuiltinFunction

type BuiltinFunction func(args []Value) (Value, error)

BuiltinFunction represents a built-in function

type BuiltinValue

type BuiltinValue struct {
	Name string
	Fn   BuiltinFunction
}

BuiltinValue represents a built-in function value

func (*BuiltinValue) Equals

func (b *BuiltinValue) Equals(other Value) bool

func (*BuiltinValue) IsTruthy

func (b *BuiltinValue) IsTruthy() bool

func (*BuiltinValue) String

func (b *BuiltinValue) String() string

func (*BuiltinValue) Type

func (b *BuiltinValue) Type() ValueType

type CacheControl

type CacheControl struct {
	Type string // "ephemeral" - marks content for caching
	TTL  string // Optional: "5m" or "1h" (Anthropic supports these TTLs)
}

CacheControl specifies caching behavior for a content part. Supported by OpenRouter when using Anthropic or Gemini models. Ignored (but safe to send) by OpenAI direct and Ollama.

type ChatMessage

type ChatMessage struct {
	Role       string // "system", "user", "assistant", "tool"
	Content    string
	Name       string         // Optional: name of the tool or user
	ToolCallID string         // For tool result messages (required by OpenAI API)
	ToolCalls  []ChatToolCall // For assistant messages that request tool calls

	// ContentParts allows multipart content with cache control for prompt caching.
	// When set, this takes precedence over Content for providers that support it.
	// Compatible with OpenAI, Ollama, and OpenRouter (Anthropic, Gemini, etc.)
	ContentParts []ContentPart
}

ChatMessage represents a single message in the conversation

type ChatRequest

type ChatRequest struct {
	// Model configuration
	Model *ModelValue

	// Messages in the conversation
	Messages []ChatMessage

	// Tools available to the agent
	Tools []ChatTool
}

ChatRequest represents a chat completion request

type ChatResponse

type ChatResponse struct {
	// The generated message
	Content string

	// Finish reason ("stop", "length", "tool_calls", etc.)
	FinishReason string

	// Token usage information
	Usage *ChatUsage

	// Tool calls requested by the model
	ToolCalls []ChatToolCall
}

ChatResponse represents a chat completion response

type ChatTool

type ChatTool struct {
	Name        string
	Description string
	Parameters  map[string]interface{}
}

ChatTool represents a tool that can be called by the model

func EditFileToolDefinition

func EditFileToolDefinition() ChatTool

EditFileToolDefinition returns the ChatTool definition for the edit_file tool.

func ExecToolDefinition

func ExecToolDefinition() ChatTool

ExecToolDefinition returns the ChatTool definition for the exec tool.

func GrepToolDefinition

func GrepToolDefinition() ChatTool

GrepToolDefinition returns the ChatTool definition for the grep tool.

func ViewFileToolDefinition

func ViewFileToolDefinition() ChatTool

ViewFileToolDefinition returns the ChatTool definition for the view_file tool.

type ChatToolCall

type ChatToolCall struct {
	ID        string
	Name      string
	Arguments map[string]interface{}
}

ChatToolCall represents a tool call requested by the model

func (ChatToolCall) MarshalJSON

func (tc ChatToolCall) MarshalJSON() ([]byte, error)

MarshalJSON is needed for tool call arguments

type ChatUsage

type ChatUsage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int

	// CachedTokens indicates how many prompt tokens were cache hits.
	CachedTokens int
}

ChatUsage represents token usage information

type ContentPart

type ContentPart struct {
	Type string // "text", "image_url"
	Text string // For "text" type
}

ContentPart represents a part of a multipart message content. Used for prompt caching with OpenRouter/Anthropic and vision content with OpenAI.

type ControlFlowError

type ControlFlowError struct {
	Signal ControlFlowSignal
	Value  Value       // For return statements
	Token  lexer.Token // Token for location information
}

ControlFlowError represents a control flow interruption

func (*ControlFlowError) Error

func (c *ControlFlowError) Error() string

type ControlFlowSignal

type ControlFlowSignal int

ControlFlowSignal represents a control flow interruption (break, continue, return)

const (
	// SignalNone indicates normal execution
	SignalNone ControlFlowSignal = iota
	// SignalBreak indicates a break statement
	SignalBreak
	// SignalContinue indicates a continue statement
	SignalContinue
	// SignalReturn indicates a return statement
	SignalReturn
)

type ConversationValue

type ConversationValue struct {
	// Messages in the conversation history
	Messages []ChatMessage
}

ConversationValue represents a conversation state

func (*ConversationValue) Equals

func (c *ConversationValue) Equals(other Value) bool

func (*ConversationValue) GetProperty added in v1.1.0

func (c *ConversationValue) GetProperty(name string) Value

GetProperty returns a property of the conversation

func (*ConversationValue) IsTruthy

func (c *ConversationValue) IsTruthy() bool

func (*ConversationValue) String

func (c *ConversationValue) String() string

func (*ConversationValue) Type

func (c *ConversationValue) Type() ValueType

type DynamicValue

type DynamicValue struct {
	Get func() Value
	Set func(Value) error
}

DynamicValue represents a value with custom get/set behavior. It implements DynamicValueGetter so it can be unwrapped via UnwrapValue().

func (*DynamicValue) Equals

func (d *DynamicValue) Equals(other Value) bool

func (*DynamicValue) GetDynamicValue

func (d *DynamicValue) GetDynamicValue() Value

GetDynamicValue implements DynamicValueGetter interface. This allows UnwrapValue() to unwrap DynamicValue to its underlying value.

func (*DynamicValue) GetProperty

func (d *DynamicValue) GetProperty(name string) Value

func (*DynamicValue) IsTruthy

func (d *DynamicValue) IsTruthy() bool

func (*DynamicValue) SetProperty

func (d *DynamicValue) SetProperty(name string, value Value) error

func (*DynamicValue) String

func (d *DynamicValue) String() string

func (*DynamicValue) Type

func (d *DynamicValue) Type() ValueType

type DynamicValueGetter

type DynamicValueGetter interface {
	GetDynamicValue() Value
}

DynamicValueGetter is an interface for values that wrap other values dynamically. This is implemented by DynamicValue to allow unwrapping without circular dependencies.

type EditResult

type EditResult struct {
	Success bool
	Message string
}

EditResult contains the result of an edit operation.

func ExecuteEdit

func ExecuteEdit(ctx context.Context, filePath, find, replace string, startLine, endLine int) (*EditResult, error)

ExecuteEdit performs a find-and-replace edit on a file. The find string must appear exactly once in the file (or within the specified line range). If startLine and endLine are provided (1-indexed, inclusive), the search is constrained to that range.

type EnvValue

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

EnvValue represents the env object for environment variable access It holds a reference to the interpreter to access the shared sh runner

func (*EnvValue) Equals

func (e *EnvValue) Equals(other Value) bool

func (*EnvValue) GetProperty

func (e *EnvValue) GetProperty(name string) Value

GetProperty gets an environment variable from the sh runner

func (*EnvValue) IsTruthy

func (e *EnvValue) IsTruthy() bool

func (*EnvValue) SetProperty

func (e *EnvValue) SetProperty(name string, value Value) error

SetProperty sets an environment variable in the sh runner

func (*EnvValue) String

func (e *EnvValue) String() string

func (*EnvValue) Type

func (e *EnvValue) Type() ValueType

type Environment

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

Environment represents a scope for variable bindings

func NewEnclosedEnvironment

func NewEnclosedEnvironment(outer *Environment) *Environment

NewEnclosedEnvironment creates a new environment enclosed by an outer environment

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment creates a new environment

func NewIsolatedEnvironment

func NewIsolatedEnvironment(outer *Environment) *Environment

NewIsolatedEnvironment creates a new environment that can read from parent but writes (updates) stay local. This is used for tool scopes to prevent scope leakage.

func (*Environment) AllKeys

func (e *Environment) AllKeys() []string

AllKeys returns all variable names in the current scope and all parent scopes

func (*Environment) Clone

func (e *Environment) Clone() *Environment

Clone creates a shallow copy of the environment (current scope only)

func (*Environment) Delete

func (e *Environment) Delete(name string) bool

Delete removes a variable from the current scope It returns true if the variable was found and deleted, false otherwise

func (*Environment) Get

func (e *Environment) Get(name string) (Value, bool)

Get retrieves a value from the environment by name It searches the current scope and all parent scopes

func (*Environment) Has

func (e *Environment) Has(name string) bool

Has checks if a variable exists in the current scope or any parent scope

func (*Environment) HasLocal

func (e *Environment) HasLocal(name string) bool

HasLocal checks if a variable exists in the current scope only (not parent scopes)

func (*Environment) Keys

func (e *Environment) Keys() []string

Keys returns all variable names in the current scope (not including parent scopes)

func (*Environment) Set

func (e *Environment) Set(name string, value Value)

Set assigns a value to a variable in the environment It always sets the variable in the current scope, potentially shadowing parent variables

func (*Environment) Update

func (e *Environment) Update(name string, value Value) error

Update updates an existing variable's value It returns an error if the variable doesn't exist For isolated environments (tool scopes), updates to parent variables create local shadows

type ErrorValue

type ErrorValue struct {
	Message string
}

ErrorValue represents an error value

func NewError

func NewError(format string, args ...interface{}) *ErrorValue

NewError creates a new error value

func (*ErrorValue) Equals

func (e *ErrorValue) Equals(other Value) bool

func (*ErrorValue) IsTruthy

func (e *ErrorValue) IsTruthy() bool

func (*ErrorValue) String

func (e *ErrorValue) String() string

func (*ErrorValue) Type

func (e *ErrorValue) Type() ValueType

type EvalResult

type EvalResult struct {
	FinalResult Value        // The value of the last statement executed
	Env         *Environment // The environment after execution (contains all variables)
}

EvalResult represents the result of evaluating a program

func (*EvalResult) Value

func (r *EvalResult) Value() Value

Value returns the final result value for convenient access

func (*EvalResult) Variables

func (r *EvalResult) Variables() map[string]Value

Variables returns all top-level variables as a map (excluding built-ins)

type EventManager

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

EventManager manages middleware chains for events. Each event has an ordered list of middleware handlers that form a chain. Middleware handlers have the signature: tool(ctx, next) where:

  • ctx: event-specific context object
  • next: function to call the next middleware in chain

Middleware can:

  • Pass through: return next(ctx)
  • Stop chain and override: return { result: ... } (don't call next)
  • Transform context: modify ctx, then return next(ctx)

func NewEventManager

func NewEventManager() *EventManager

NewEventManager creates a new event manager

func (*EventManager) GetHandlers

func (em *EventManager) GetHandlers(eventName string) []*ToolValue

GetHandlers returns all handlers for a given event in registration order

func (*EventManager) HasHandlers added in v1.1.0

func (em *EventManager) HasHandlers(eventName string) bool

HasHandlers returns true if there are any handlers for the given event

func (*EventManager) Remove added in v1.1.0

func (em *EventManager) Remove(eventName string, handler *ToolValue) bool

Remove removes a middleware handler by tool reference. Returns true if removed, false if not found.

func (*EventManager) RemoveAll added in v1.1.0

func (em *EventManager) RemoveAll(eventName string) int

RemoveAll removes all handlers for an event. Returns the number of handlers removed.

func (*EventManager) RemoveByID added in v1.1.0

func (em *EventManager) RemoveByID(eventName string, handlerID string) bool

RemoveByID removes a middleware handler by its ID. Returns true if removed, false if not found.

func (*EventManager) Use added in v1.1.0

func (em *EventManager) Use(eventName string, handler *ToolValue) string

Use registers a middleware handler for an event and returns a unique handler ID. Middleware runs in registration order (first registered = first to run).

type ExecResult

type ExecResult struct {
	Output   string // Combined stdout/stderr (PTY combines them)
	ExitCode int
}

ExecResult contains the result of executing a shell command.

func ExecuteCommandWithPTY

func ExecuteCommandWithPTY(ctx context.Context, command string, liveOutput io.Writer, workingDir string) (*ExecResult, error)

ExecuteCommandWithPTY runs a shell command with PTY support. This allows live output display while also capturing the output. The liveOutput writer receives output in real-time as the command runs. If liveOutput is nil, output is only captured (not displayed). The workingDir parameter specifies the directory to run the command in.

type GrepBackend

type GrepBackend int

GrepBackend represents the grep implementation to use.

const (
	GrepBackendNone GrepBackend = iota
	GrepBackendRipgrep
	GrepBackendGitGrep
	GrepBackendGrep
)

func DetectGrepBackend

func DetectGrepBackend() GrepBackend

DetectGrepBackend determines which grep backend to use based on available tools. Priority: rg > git grep (if in git repo) > grep > none

type GrepResult

type GrepResult struct {
	Output   string
	ExitCode int
	Backend  string
}

GrepResult contains the result of a grep search.

func ExecuteGrep

func ExecuteGrep(ctx context.Context, pattern string, workingDir string) (*GrepResult, error)

ExecuteGrep runs a grep search with the detected backend in the specified directory.

func ExecuteGrepWithBackend

func ExecuteGrepWithBackend(ctx context.Context, pattern string, backend GrepBackend, workingDir string) (*GrepResult, error)

ExecuteGrepWithBackend runs a grep search with a specific backend in the specified directory.

type GshObjectValue

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

GshObjectValue represents the gsh SDK object with custom property handling

func (*GshObjectValue) Equals

func (g *GshObjectValue) Equals(other Value) bool

func (*GshObjectValue) GetProperty

func (g *GshObjectValue) GetProperty(name string) Value

func (*GshObjectValue) IsTruthy

func (g *GshObjectValue) IsTruthy() bool

func (*GshObjectValue) SetProperty

func (g *GshObjectValue) SetProperty(name string, value Value) error

func (*GshObjectValue) String

func (g *GshObjectValue) String() string

func (*GshObjectValue) Type

func (g *GshObjectValue) Type() ValueType

type HistoryEntry added in v1.2.0

type HistoryEntry struct {
	Command   string
	Timestamp int64
	ExitCode  int
}

HistoryEntry represents a single command history entry

type HistoryProvider added in v1.2.0

type HistoryProvider interface {
	// FindPrefix returns history entries matching the given prefix, ordered by most recent first.
	// The limit parameter controls the maximum number of entries to search.
	FindPrefix(prefix string, limit int) ([]HistoryEntry, error)
	// GetRecent returns the most recent history entries in chronological order
	// (oldest first, most recent last). The limit parameter controls the maximum
	// number of entries to return.
	GetRecent(limit int) ([]HistoryEntry, error)
}

HistoryProvider provides access to command history for gsh scripts

type Indexable

type Indexable interface {
	Value
	GetIndex(index int) Value
}

Indexable is an interface for values that support index-based access (e.g., array[0])

type Interpreter

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

Interpreter represents the gsh script interpreter

func New

func New(opts *Options) *Interpreter

New creates a new interpreter with the given options. Pass nil for default options.

func (*Interpreter) CallTool

func (i *Interpreter) CallTool(tool *ToolValue, args []Value) (Value, error)

callTool executes a tool with the given arguments CallTool calls a tool with the given arguments

func (*Interpreter) Close

func (i *Interpreter) Close() error

Close cleans up resources used by the interpreter

func (*Interpreter) Context added in v1.1.1

func (i *Interpreter) Context() context.Context

Context returns the current execution context. If no context has been set, returns context.Background(). This should be used by operations that support cancellation.

func (*Interpreter) EmitEvent

func (i *Interpreter) EmitEvent(eventName string, ctx Value) Value

EmitEvent emits an event by executing the middleware chain. Each middleware handler receives (ctx, next) where:

  • ctx: event-specific context object
  • next: function to call the next middleware in chain

Middleware can:

  • Pass through: return next(ctx) - continues to next middleware
  • Stop chain and override: return { ... } without calling next
  • Transform context: modify ctx, then return next(ctx)

The return value from the chain (if any non-null value) can be used to override default behavior. The interpretation is event-specific.

func (*Interpreter) Eval

func (i *Interpreter) Eval(program *parser.Program) (*EvalResult, error)

Eval evaluates a program and returns the result

func (*Interpreter) EvalString

func (i *Interpreter) EvalString(source string, origin *ScriptOrigin) (*EvalResult, error)

EvalString parses and evaluates a source string in the interpreter. Pass nil for origin if no import resolution is needed (e.g., REPL input). For filesystem scripts, pass a ScriptOrigin with Type=OriginFilesystem. For embedded scripts, pass a ScriptOrigin with Type=OriginEmbed and EmbedFS set.

func (*Interpreter) ExecuteAgent

func (i *Interpreter) ExecuteAgent(
	ctx context.Context,
	conv *ConversationValue,
	agent *AgentValue,
	streaming bool,
) (Value, error)

ExecuteAgent executes an agent with a conversation and returns the updated conversation. streaming parameter enables streaming responses. SDK events (agent.start, agent.end, etc.) are emitted via the interpreter's event manager. The user message is inferred from the conversation.

func (*Interpreter) ExecuteAgentWithCallbacks

func (i *Interpreter) ExecuteAgentWithCallbacks(
	ctx context.Context,
	conv *ConversationValue,
	agent *AgentValue,
	streaming bool,
	callbacks *AgentCallbacks,
) (Value, error)

ExecuteAgentWithCallbacks executes an agent with callbacks and returns the updated conversation. streaming parameter enables streaming responses. callbacks can be used to hook into agent execution events (tool execution, streaming chunks, etc.). SDK events (agent.start, agent.end, etc.) are emitted via the interpreter's event manager regardless of callbacks. The user message is inferred from the conversation.

func (*Interpreter) GetEnv

func (i *Interpreter) GetEnv(name string) string

GetEnv returns an environment variable It first checks runner.Vars (for variables set during the session), then falls back to os.Getenv (for inherited environment variables)

func (*Interpreter) GetEventHandlers

func (i *Interpreter) GetEventHandlers(eventName string) []*ToolValue

GetEventHandlers returns all registered handlers for a given event name

func (*Interpreter) GetVariables

func (i *Interpreter) GetVariables() map[string]Value

GetVariables returns all top-level variables from the interpreter's environment (excluding built-ins)

func (*Interpreter) GetWorkingDir

func (i *Interpreter) GetWorkingDir() string

GetWorkingDir returns the current working directory from the sh runner

func (*Interpreter) InjectACPSession added in v1.1.0

func (i *Interpreter) InjectACPSession(agentName, sessionID string, session acp.ACPSession)

InjectACPSession injects a mock ACP session for testing. This bypasses the normal client creation and allows direct session injection.

func (*Interpreter) Runner

func (i *Interpreter) Runner() *interp.Runner

Runner returns the underlying sh runner This is used by the REPL executor to share the same runner for bash commands

func (*Interpreter) RunnerMutex

func (i *Interpreter) RunnerMutex() *sync.RWMutex

RunnerMutex returns the mutex protecting the runner The REPL executor should hold this lock when accessing the runner

func (*Interpreter) SDKConfig

func (i *Interpreter) SDKConfig() *SDKConfig

SDKConfig returns the SDK configuration

func (*Interpreter) SetACPClientFactory added in v1.1.0

func (i *Interpreter) SetACPClientFactory(factory ACPClientFactory)

SetACPClientFactory sets a custom factory for creating ACP clients. This is primarily used for testing with mock clients.

func (*Interpreter) SetContext added in v1.1.1

func (i *Interpreter) SetContext(ctx context.Context)

SetContext sets the execution context for the interpreter. This context is used for cancellation (e.g., when Ctrl+C is pressed). The REPL sets this before executing commands so that long-running operations (like agent execution or shell commands) can be cancelled.

func (*Interpreter) SetEnv

func (i *Interpreter) SetEnv(name, value string)

SetEnv sets an environment variable by running an export command through the runner This ensures the variable is properly inherited by subshells

func (*Interpreter) SetStdin

func (i *Interpreter) SetStdin(r io.Reader)

SetStdin sets the stdin reader for the input() function This is useful for testing or for providing custom input sources

func (*Interpreter) SetVariable

func (i *Interpreter) SetVariable(name string, value Value)

SetVariable defines or updates a variable in the interpreter's environment

func (*Interpreter) UnsetEnv

func (i *Interpreter) UnsetEnv(name string)

UnsetEnv removes an environment variable by running an unset command through the runner This ensures the variable is properly removed from subshells

type LastCommandObjectValue

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

LastCommandObjectValue represents the gsh.lastCommand object

func (*LastCommandObjectValue) Equals

func (c *LastCommandObjectValue) Equals(other Value) bool

func (*LastCommandObjectValue) GetProperty

func (c *LastCommandObjectValue) GetProperty(name string) Value

func (*LastCommandObjectValue) IsTruthy

func (c *LastCommandObjectValue) IsTruthy() bool

func (*LastCommandObjectValue) SetProperty

func (c *LastCommandObjectValue) SetProperty(name string, value Value) error

func (*LastCommandObjectValue) String

func (c *LastCommandObjectValue) String() string

func (*LastCommandObjectValue) Type

type LoggingObjectValue

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

LoggingObjectValue represents the gsh.logging object with dynamic properties

func (*LoggingObjectValue) Equals

func (l *LoggingObjectValue) Equals(other Value) bool

func (*LoggingObjectValue) GetProperty

func (l *LoggingObjectValue) GetProperty(name string) Value

func (*LoggingObjectValue) IsTruthy

func (l *LoggingObjectValue) IsTruthy() bool

func (*LoggingObjectValue) SetProperty

func (l *LoggingObjectValue) SetProperty(name string, value Value) error

func (*LoggingObjectValue) String

func (l *LoggingObjectValue) String() string

func (*LoggingObjectValue) Type

func (l *LoggingObjectValue) Type() ValueType

type MCPProxyValue

type MCPProxyValue struct {
	ServerName string
	Manager    *mcp.Manager
}

MCPProxyValue represents a proxy object for an MCP server It allows calling tools via member expressions (e.g., filesystem.read_file)

func (*MCPProxyValue) Equals

func (m *MCPProxyValue) Equals(other Value) bool

func (*MCPProxyValue) GetProperty

func (m *MCPProxyValue) GetProperty(name string) (Value, error)

GetProperty returns a tool from this MCP server

func (*MCPProxyValue) IsTruthy

func (m *MCPProxyValue) IsTruthy() bool

func (*MCPProxyValue) String

func (m *MCPProxyValue) String() string

func (*MCPProxyValue) Type

func (m *MCPProxyValue) Type() ValueType

type MCPToolValue

type MCPToolValue struct {
	ServerName string
	ToolName   string
	Manager    *mcp.Manager
}

MCPToolValue represents a specific MCP tool that can be called

func (*MCPToolValue) Call

func (m *MCPToolValue) Call(args map[string]interface{}) (Value, error)

Call invokes the MCP tool with the given arguments

func (*MCPToolValue) Equals

func (m *MCPToolValue) Equals(other Value) bool

func (*MCPToolValue) IsTruthy

func (m *MCPToolValue) IsTruthy() bool

func (*MCPToolValue) String

func (m *MCPToolValue) String() string

func (*MCPToolValue) Type

func (m *MCPToolValue) Type() ValueType

type MapMethodValue

type MapMethodValue struct {
	Name string
	Impl mapMethodImpl
	Map  *MapValue // The map instance this method is bound to
}

MapMethodValue wraps a map method that needs to be bound to an instance at call time

func (*MapMethodValue) Equals

func (m *MapMethodValue) Equals(other Value) bool

func (*MapMethodValue) IsTruthy

func (m *MapMethodValue) IsTruthy() bool

func (*MapMethodValue) String

func (m *MapMethodValue) String() string

func (*MapMethodValue) Type

func (m *MapMethodValue) Type() ValueType

type MapValue

type MapValue struct {
	Entries map[string]Value
}

MapValue represents a map value (key-value pairs)

func (*MapValue) Equals

func (m *MapValue) Equals(other Value) bool

func (*MapValue) IsTruthy

func (m *MapValue) IsTruthy() bool

func (*MapValue) String

func (m *MapValue) String() string

func (*MapValue) Type

func (m *MapValue) Type() ValueType

type MockProvider

type MockProvider struct {

	// ResponseMap maps input prompts to responses
	ResponseMap map[string]string
	// DefaultResponse is used if no mapping found
	DefaultResponse string
	// ToolCallScenarios defines when to make tool calls
	ToolCallScenarios map[string][]ChatToolCall
	// CallHistory tracks all calls made
	CallHistory []ChatRequest
	// contains filtered or unexported fields
}

MockProvider is a test provider that returns predictable responses

func NewMockProvider

func NewMockProvider() *MockProvider

NewMockProvider creates a new mock provider

func (*MockProvider) ChatCompletion

func (m *MockProvider) ChatCompletion(ctx context.Context, request ChatRequest) (*ChatResponse, error)

ChatCompletion simulates an LLM response

func (*MockProvider) GetCallCount

func (m *MockProvider) GetCallCount() int

GetCallCount returns the number of calls made

func (*MockProvider) GetLastRequest

func (m *MockProvider) GetLastRequest() *ChatRequest

GetLastRequest returns the last request made

func (*MockProvider) Name

func (m *MockProvider) Name() string

Name returns the provider name

func (*MockProvider) Reset

func (m *MockProvider) Reset()

Reset clears the call history

func (*MockProvider) SetResponse

func (m *MockProvider) SetResponse(input, response string)

SetResponse sets a specific response for a given input

func (*MockProvider) SetToolCallScenario

func (m *MockProvider) SetToolCallScenario(input string, toolCalls []ChatToolCall)

SetToolCallScenario sets up a tool call scenario

func (*MockProvider) StreamingChatCompletion

func (m *MockProvider) StreamingChatCompletion(ctx context.Context, request ChatRequest, callback StreamCallback) (*ChatResponse, error)

StreamingChatCompletion simulates streaming by calling the callback with the full response

type ModelProvider

type ModelProvider interface {
	// Name returns the provider name (e.g., "openai", "anthropic")
	Name() string

	// ChatCompletion sends a chat completion request.
	// The ctx parameter allows cancellation of the request (e.g., via Ctrl+C).
	ChatCompletion(ctx context.Context, request ChatRequest) (*ChatResponse, error)

	// StreamingChatCompletion sends a chat completion request with streaming response.
	// The ctx parameter allows cancellation of the streaming request (e.g., via Ctrl+C).
	// The callbacks provide hooks for content chunks and tool call detection.
	// Returns the final complete response after streaming is done.
	StreamingChatCompletion(ctx context.Context, request ChatRequest, callbacks *StreamCallbacks) (*ChatResponse, error)
}

ModelProvider defines the interface for LLM model providers

type ModelResolver

type ModelResolver interface {
	Value
	// GetModel resolves to a concrete ModelValue.
	// For direct ModelValue assignments, this returns itself.
	// For SDK model references, this looks up the current value from the internal Models registry.
	GetModel() *ModelValue
}

ModelResolver is an interface for values that can resolve to a ModelValue. This enables lazy model resolution for SDK model references (gsh.models.lite, etc.) while still allowing direct ModelValue assignment.

type ModelValue

type ModelValue struct {
	Name     string
	Config   map[string]Value
	Provider ModelProvider
}

ModelValue represents a model configuration

func (*ModelValue) ChatCompletion

func (m *ModelValue) ChatCompletion(ctx context.Context, request ChatRequest) (*ChatResponse, error)

ChatCompletion performs a chat completion using this model's provider. This is a convenience method that delegates to the model's provider. The ctx parameter allows cancellation of the request (e.g., via Ctrl+C).

func (*ModelValue) Equals

func (m *ModelValue) Equals(other Value) bool

func (*ModelValue) GetModel

func (m *ModelValue) GetModel() *ModelValue

GetModel implements ModelResolver interface. For a direct ModelValue, it simply returns itself.

func (*ModelValue) GetProperty

func (m *ModelValue) GetProperty(name string) Value

GetProperty returns a property of the model

func (*ModelValue) IsTruthy

func (m *ModelValue) IsTruthy() bool

func (*ModelValue) SetProperty

func (m *ModelValue) SetProperty(name string, value Value) error

SetProperty sets a property of the model (read-only, so always errors)

func (*ModelValue) StreamingChatCompletion

func (m *ModelValue) StreamingChatCompletion(ctx context.Context, request ChatRequest, callbacks *StreamCallbacks) (*ChatResponse, error)

StreamingChatCompletion performs a streaming chat completion using this model's provider. This is a convenience method that delegates to the model's provider. The ctx parameter allows cancellation of the streaming request (e.g., via Ctrl+C).

func (*ModelValue) String

func (m *ModelValue) String() string

func (*ModelValue) Type

func (m *ModelValue) Type() ValueType

type Models

type Models struct {
	Lite      *ModelValue
	Workhorse *ModelValue
	Premium   *ModelValue
}

Models holds the model tier definitions (available in both REPL and script mode)

type ModelsObjectValue

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

ModelsObjectValue represents the gsh.models object. It holds pre-created SDKModelRef instances for each tier to avoid allocations on repeated access and to maintain pointer identity.

func NewModelsObjectValue

func NewModelsObjectValue(models *Models) *ModelsObjectValue

NewModelsObjectValue creates a new ModelsObjectValue with pre-allocated SDKModelRef instances.

func (*ModelsObjectValue) Equals

func (m *ModelsObjectValue) Equals(other Value) bool

func (*ModelsObjectValue) GetProperty

func (m *ModelsObjectValue) GetProperty(name string) Value

func (*ModelsObjectValue) IsTruthy

func (m *ModelsObjectValue) IsTruthy() bool

func (*ModelsObjectValue) SetProperty

func (m *ModelsObjectValue) SetProperty(name string, value Value) error

func (*ModelsObjectValue) String

func (m *ModelsObjectValue) String() string

func (*ModelsObjectValue) Type

func (m *ModelsObjectValue) Type() ValueType

type NativeToolValue

type NativeToolValue struct {
	Name        string                                                 // Tool name (e.g., "exec", "grep")
	Description string                                                 // Human-readable description
	Parameters  map[string]interface{}                                 // JSON schema for parameters
	Invoke      func(args map[string]interface{}) (interface{}, error) // Go implementation
}

NativeToolValue represents a native (Go-implemented) tool that can be used by agents. Unlike BuiltinValue which is for simple functions, NativeToolValue provides full tool metadata (description, parameters) needed for LLM tool calling.

func CreateEditFileNativeTool

func CreateEditFileNativeTool() *NativeToolValue

CreateEditFileNativeTool creates the edit_file native tool for use in gsh.tools.

func CreateExecNativeTool

func CreateExecNativeTool() *NativeToolValue

CreateExecNativeTool creates the exec native tool for use in gsh.tools. Output is streamed to stderr in real-time.

func CreateGrepNativeTool

func CreateGrepNativeTool() *NativeToolValue

CreateGrepNativeTool creates the grep native tool for use in gsh.tools.

func CreateViewFileNativeTool

func CreateViewFileNativeTool() *NativeToolValue

CreateViewFileNativeTool creates the view_file native tool for use in gsh.tools.

func (*NativeToolValue) Equals

func (n *NativeToolValue) Equals(other Value) bool

func (*NativeToolValue) IsTruthy

func (n *NativeToolValue) IsTruthy() bool

func (*NativeToolValue) String

func (n *NativeToolValue) String() string

func (*NativeToolValue) Type

func (n *NativeToolValue) Type() ValueType

type NullValue

type NullValue struct{}

NullValue represents a null value

func (*NullValue) Equals

func (n *NullValue) Equals(other Value) bool

func (*NullValue) IsTruthy

func (n *NullValue) IsTruthy() bool

func (*NullValue) String

func (n *NullValue) String() string

func (*NullValue) Type

func (n *NullValue) Type() ValueType

type NumberMethodValue

type NumberMethodValue struct {
	Name string
	Impl numberMethodImpl
	Num  *NumberValue // The number instance this method is bound to
}

NumberMethodValue wraps a number method that needs to be bound to an instance at call time

func (*NumberMethodValue) Equals

func (n *NumberMethodValue) Equals(other Value) bool

func (*NumberMethodValue) IsTruthy

func (n *NumberMethodValue) IsTruthy() bool

func (*NumberMethodValue) String

func (n *NumberMethodValue) String() string

func (*NumberMethodValue) Type

func (n *NumberMethodValue) Type() ValueType

type NumberValue

type NumberValue struct {
	Value float64
}

NumberValue represents a number value

func (*NumberValue) Equals

func (n *NumberValue) Equals(other Value) bool

func (*NumberValue) IsTruthy

func (n *NumberValue) IsTruthy() bool

func (*NumberValue) String

func (n *NumberValue) String() string

func (*NumberValue) Type

func (n *NumberValue) Type() ValueType

type ObjectMethodValue

type ObjectMethodValue struct {
	Name string
	Impl objectMethodImpl
	Obj  *ObjectValue // The object instance this method is bound to
}

ObjectMethodValue wraps an object method that needs to be bound to an instance at call time

func (*ObjectMethodValue) Equals

func (o *ObjectMethodValue) Equals(other Value) bool

func (*ObjectMethodValue) IsTruthy

func (o *ObjectMethodValue) IsTruthy() bool

func (*ObjectMethodValue) String

func (o *ObjectMethodValue) String() string

func (*ObjectMethodValue) Type

func (o *ObjectMethodValue) Type() ValueType

type ObjectValue

type ObjectValue struct {
	Properties map[string]*PropertyDescriptor
}

ObjectValue represents an object value

func (*ObjectValue) DeepCopy

func (o *ObjectValue) DeepCopy() *ObjectValue

DeepCopy creates a completely independent deep copy of the ObjectValue. Modifying the copy will not affect the original object.

func (*ObjectValue) DeepMerge

func (o *ObjectValue) DeepMerge(override *ObjectValue) *ObjectValue

DeepMerge creates a new ObjectValue by deeply merging this object with another. Properties from the override object take precedence over properties in this object. When both objects have a property with the same key and both values are ObjectValues, those nested objects are recursively merged. Otherwise, the override value replaces the base value entirely.

The returned ObjectValue is completely independent - modifying it will not affect either the receiver or the override object.

func (*ObjectValue) Equals

func (o *ObjectValue) Equals(other Value) bool

func (*ObjectValue) GetPropertyValue

func (o *ObjectValue) GetPropertyValue(key string) Value

GetPropertyValue gets the actual value of a property, handling getters

func (*ObjectValue) IsTruthy

func (o *ObjectValue) IsTruthy() bool

func (*ObjectValue) SetPropertyValue

func (o *ObjectValue) SetPropertyValue(key string, value Value) error

SetPropertyValue sets a property value, respecting read-only and custom setters

func (*ObjectValue) String

func (o *ObjectValue) String() string

func (*ObjectValue) Type

func (o *ObjectValue) Type() ValueType

type OpenAIProvider

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

OpenAIProvider implements the ModelProvider interface for OpenAI

func NewOpenAIProvider

func NewOpenAIProvider() *OpenAIProvider

NewOpenAIProvider creates a new OpenAI provider

func (*OpenAIProvider) ChatCompletion

func (p *OpenAIProvider) ChatCompletion(ctx context.Context, request ChatRequest) (*ChatResponse, error)

ChatCompletion sends a chat completion request to OpenAI. The ctx parameter allows cancellation of the request (e.g., via Ctrl+C).

func (*OpenAIProvider) Name

func (p *OpenAIProvider) Name() string

Name returns the provider name

func (*OpenAIProvider) StreamingChatCompletion

func (p *OpenAIProvider) StreamingChatCompletion(ctx context.Context, request ChatRequest, callbacks *StreamCallbacks) (*ChatResponse, error)

StreamingChatCompletion sends a chat completion request with streaming response. The ctx parameter allows cancellation of the streaming request (e.g., via Ctrl+C). The callbacks provide hooks for content chunks and tool call detection.

type Options

type Options struct {
	// Env is a custom gsh environment. If nil, a new one is created.
	Env *Environment
	// Logger is a zap logger for log.* functions. If nil, log.* writes to stderr.
	Logger *zap.Logger
	// LogLevel is an AtomicLevel for dynamic log level changes.
	// If nil/zero value, a default InfoLevel is created.
	LogLevel zap.AtomicLevel
	// Runner is a sh runner for bash execution. If nil, a new one is created.
	// Sharing a runner allows the interpreter to inherit env vars and working directory.
	Runner *interp.Runner
	// Version is the gsh version string. If empty, "unknown" is used.
	Version string
}

Options configures the interpreter. All fields are optional - nil/zero values use sensible defaults.

type OriginType

type OriginType string

OriginType represents the origin of a script

const (
	// OriginEmbed indicates a script embedded in the binary
	OriginEmbed OriginType = "embed"
	// OriginFilesystem indicates a script on the filesystem
	OriginFilesystem OriginType = "filesystem"
)

type PredictTrigger added in v1.2.0

type PredictTrigger string

PredictTrigger represents the trigger type for prediction events

const (
	// PredictTriggerInstant is used for instant predictions (must be fast, e.g., history lookup)
	PredictTriggerInstant PredictTrigger = "instant"
	// PredictTriggerDebounced is used for debounced predictions (can be slow, e.g., LLM)
	PredictTriggerDebounced PredictTrigger = "debounced"
)

type PropertyDescriptor

type PropertyDescriptor struct {
	Value    Value             // Static value (used if Getter is nil)
	ReadOnly bool              // Whether the property is read-only
	Getter   func() Value      // Dynamic getter (takes precedence over Value)
	Setter   func(Value) error // Custom setter (for validation/side effects)
}

PropertyDescriptor represents metadata about an object property

type ProviderRegistry

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

ProviderRegistry manages model providers

func NewProviderRegistry

func NewProviderRegistry() *ProviderRegistry

NewProviderRegistry creates a new provider registry

func (*ProviderRegistry) Get

func (r *ProviderRegistry) Get(name string) (ModelProvider, bool)

Get retrieves a provider by name

func (*ProviderRegistry) Register

func (r *ProviderRegistry) Register(provider ModelProvider)

Register registers a model provider

type REPLContext

type REPLContext struct {
	LastCommand *REPLLastCommand
	PromptValue Value        // Prompt string set by event handlers (read/write via gsh.prompt)
	Interpreter *Interpreter // Reference to interpreter for event execution
}

REPLContext holds REPL-specific state that's available in the SDK

type REPLLastCommand

type REPLLastCommand struct {
	Command    string
	ExitCode   int
	DurationMs int64
}

REPLLastCommand holds information about the last executed command

type RuntimeError

type RuntimeError struct {
	Message    string
	StackTrace []StackFrame
}

RuntimeError represents an error that occurred during script execution It includes a stack trace for debugging

func NewRuntimeError

func NewRuntimeError(format string, args ...interface{}) *RuntimeError

NewRuntimeError creates a new runtime error with a message

func WrapError

func WrapError(err error, location string) *RuntimeError

WrapError wraps a standard error as a RuntimeError

func (*RuntimeError) AddStackFrame

func (e *RuntimeError) AddStackFrame(functionName, location string)

AddStackFrame adds a frame to the stack trace

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

Error implements the error interface

type SDKConfig

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

SDKConfig manages runtime configuration for the SDK

func NewSDKConfig

func NewSDKConfig(logger *zap.Logger, atomicLevel zap.AtomicLevel) *SDKConfig

NewSDKConfig creates a new SDK configuration The logger should have been created with an AtomicLevel for dynamic level changes to work

func (*SDKConfig) GetHistoryProvider added in v1.2.0

func (sc *SDKConfig) GetHistoryProvider() HistoryProvider

GetHistoryProvider returns the history provider (nil in script mode)

func (*SDKConfig) GetLastAgentRequest

func (sc *SDKConfig) GetLastAgentRequest() Value

GetLastAgentRequest returns the last agent request data

func (*SDKConfig) GetLogFile

func (sc *SDKConfig) GetLogFile() string

GetLogFile returns the current log file path (read-only)

func (*SDKConfig) GetLogLevel

func (sc *SDKConfig) GetLogLevel() string

GetLogLevel returns the current log level

func (*SDKConfig) GetModels

func (sc *SDKConfig) GetModels() *Models

GetModels returns the models configuration (available in both REPL and script mode)

func (*SDKConfig) GetREPLContext

func (sc *SDKConfig) GetREPLContext() *REPLContext

GetREPLContext returns the REPL context (nil in script mode)

func (*SDKConfig) GetTermHeight

func (sc *SDKConfig) GetTermHeight() int

GetTermHeight returns the terminal height

func (*SDKConfig) GetTermWidth

func (sc *SDKConfig) GetTermWidth() int

GetTermWidth returns the terminal width

func (*SDKConfig) IsTTY

func (sc *SDKConfig) IsTTY() bool

IsTTY returns whether stdout is a TTY

func (*SDKConfig) SetHistoryProvider added in v1.2.0

func (sc *SDKConfig) SetHistoryProvider(provider HistoryProvider)

SetHistoryProvider sets the history provider for gsh.history access

func (*SDKConfig) SetLastAgentRequest

func (sc *SDKConfig) SetLastAgentRequest(value Value)

SetLastAgentRequest sets the last agent request data

func (*SDKConfig) SetLogLevel

func (sc *SDKConfig) SetLogLevel(level string) error

SetLogLevel sets the log level dynamically

func (*SDKConfig) SetREPLContext

func (sc *SDKConfig) SetREPLContext(ctx *REPLContext)

SetREPLContext sets the REPL context (called from REPL initialization)

func (*SDKConfig) UpdateLastCommand

func (sc *SDKConfig) UpdateLastCommand(command string, exitCode int, durationMs int64)

UpdateLastCommand updates the last command's info including the command string, exit code and duration

type SDKModelRef

type SDKModelRef struct {
	Tier   string  // "lite", "workhorse", or "premium"
	Models *Models // Reference to the models registry for resolution
}

SDKModelRef represents a lazy reference to a model tier (gsh.models.lite, etc.). Instead of storing a concrete ModelValue at declaration time, this stores which tier to look up, enabling dynamic model resolution at runtime.

func (*SDKModelRef) Equals

func (r *SDKModelRef) Equals(other Value) bool

func (*SDKModelRef) GetModel

func (r *SDKModelRef) GetModel() *ModelValue

GetModel resolves the SDK model reference to a concrete ModelValue by looking up the current value from the internal Models registry.

func (*SDKModelRef) GetProperty

func (r *SDKModelRef) GetProperty(name string) Value

GetProperty forwards property access to the resolved ModelValue. This allows gsh.models.lite.name to work transparently.

func (*SDKModelRef) IsTruthy

func (r *SDKModelRef) IsTruthy() bool

func (*SDKModelRef) SetProperty

func (r *SDKModelRef) SetProperty(name string, value Value) error

SetProperty forwards property setting to the resolved ModelValue.

func (*SDKModelRef) String

func (r *SDKModelRef) String() string

func (*SDKModelRef) Type

func (r *SDKModelRef) Type() ValueType

type ScriptOrigin

type ScriptOrigin struct {
	Type     OriginType // "embed" or "filesystem"
	BasePath string     // Directory containing the script
	EmbedFS  fs.FS      // Embedded filesystem (only used when Type is OriginEmbed)
}

ScriptOrigin represents the origin of a script being executed

type SetMethodValue

type SetMethodValue struct {
	Name string
	Impl setMethodImpl
	Set  *SetValue // The set instance this method is bound to
}

SetMethodValue wraps a set method that needs to be bound to an instance at call time

func (*SetMethodValue) Equals

func (s *SetMethodValue) Equals(other Value) bool

func (*SetMethodValue) IsTruthy

func (s *SetMethodValue) IsTruthy() bool

func (*SetMethodValue) String

func (s *SetMethodValue) String() string

func (*SetMethodValue) Type

func (s *SetMethodValue) Type() ValueType

type SetValue

type SetValue struct {
	Elements map[string]Value // Using map for uniqueness, key is String() representation
}

SetValue represents a set value (unique values)

func (*SetValue) Equals

func (s *SetValue) Equals(other Value) bool

func (*SetValue) IsTruthy

func (s *SetValue) IsTruthy() bool

func (*SetValue) String

func (s *SetValue) String() string

func (*SetValue) Type

func (s *SetValue) Type() ValueType

type SmartMockProvider

type SmartMockProvider struct {
	CallHistory []ChatRequest
	// contains filtered or unexported fields
}

SmartMockProvider is a more intelligent mock that can handle basic math and tool calls

func NewSmartMockProvider

func NewSmartMockProvider() *SmartMockProvider

NewSmartMockProvider creates a new smart mock provider

func (*SmartMockProvider) ChatCompletion

func (s *SmartMockProvider) ChatCompletion(ctx context.Context, request ChatRequest) (*ChatResponse, error)

ChatCompletion simulates an intelligent LLM response

func (*SmartMockProvider) GetCallCount

func (s *SmartMockProvider) GetCallCount() int

GetCallCount returns the number of calls made

func (*SmartMockProvider) GetLastRequest

func (s *SmartMockProvider) GetLastRequest() *ChatRequest

GetLastRequest returns the last request made

func (*SmartMockProvider) Name

func (s *SmartMockProvider) Name() string

Name returns the provider name

func (*SmartMockProvider) Reset

func (s *SmartMockProvider) Reset()

Reset clears the call history

func (*SmartMockProvider) StreamingChatCompletion

func (s *SmartMockProvider) StreamingChatCompletion(ctx context.Context, request ChatRequest, callbacks *StreamCallbacks) (*ChatResponse, error)

StreamingChatCompletion simulates streaming by calling the callbacks with the full response

type StackFrame

type StackFrame struct {
	FunctionName string // Name of the function/tool being executed
	Location     string // Source location (line:column or description)
}

StackFrame represents a single frame in the call stack

type StreamCallback

type StreamCallback func(content string)

StreamCallback is called for each chunk of streamed content. The content parameter contains the incremental text delta.

type StreamCallbacks

type StreamCallbacks struct {
	// OnContent is called for each chunk of content text.
	OnContent func(content string)

	// OnToolPending is called when a tool call enters pending state (starts streaming).
	// At this point, the tool ID and name are known but arguments may still be streaming.
	OnToolPending func(toolCallID string, toolName string)

	// ShouldCancel is called periodically during streaming to check if the operation
	// should be cancelled (e.g., due to Ctrl+C). Returns true to cancel.
	// If nil, cancellation checking is skipped.
	ShouldCancel func() bool
}

StreamCallbacks provides extended callbacks for streaming responses. This allows for more granular control over streaming, including tool call detection.

type StringMethodValue

type StringMethodValue struct {
	Name string
	Impl stringMethodImpl
	Str  *StringValue // The string instance this method is bound to
}

StringMethodValue wraps a string method that needs to be bound to an instance at call time

func (*StringMethodValue) Equals

func (s *StringMethodValue) Equals(other Value) bool

func (*StringMethodValue) IsTruthy

func (s *StringMethodValue) IsTruthy() bool

func (*StringMethodValue) String

func (s *StringMethodValue) String() string

func (*StringMethodValue) Type

func (s *StringMethodValue) Type() ValueType

type StringValue

type StringValue struct {
	Value string
}

StringValue represents a string value

func (*StringValue) Equals

func (s *StringValue) Equals(other Value) bool

func (*StringValue) IsTruthy

func (s *StringValue) IsTruthy() bool

func (*StringValue) String

func (s *StringValue) String() string

func (*StringValue) Type

func (s *StringValue) Type() ValueType

type ToolOverride

type ToolOverride struct {
	Result string // The result to use instead of actual tool execution
	Error  string // Optional error message (if set, tool is considered failed)
}

ToolOverride represents an override returned by an event handler for tool events. Used by agent.tool.start and agent.tool.end event handlers to override tool execution.

type ToolValue

type ToolValue struct {
	Name       string
	Parameters []string
	ParamTypes map[string]string // parameter name -> type annotation (optional)
	ReturnType string            // return type annotation (optional)
	Body       interface{}       // *parser.BlockStatement for user-defined tools
	Env        *Environment      // closure environment
}

ToolValue represents a tool/function value

func (*ToolValue) Equals

func (t *ToolValue) Equals(other Value) bool

func (*ToolValue) IsTruthy

func (t *ToolValue) IsTruthy() bool

func (*ToolValue) String

func (t *ToolValue) String() string

func (*ToolValue) Type

func (t *ToolValue) Type() ValueType

type UICursorObject

type UICursorObject struct{}

UICursorObject provides cursor control methods

type UICursorObjectValue

type UICursorObjectValue struct{}

UICursorObjectValue represents gsh.ui.cursor

func (*UICursorObjectValue) Equals

func (c *UICursorObjectValue) Equals(other Value) bool

func (*UICursorObjectValue) GetProperty

func (c *UICursorObjectValue) GetProperty(name string) Value

func (*UICursorObjectValue) IsTruthy

func (c *UICursorObjectValue) IsTruthy() bool

func (*UICursorObjectValue) SetProperty

func (c *UICursorObjectValue) SetProperty(name string, value Value) error

func (*UICursorObjectValue) String

func (c *UICursorObjectValue) String() string

func (*UICursorObjectValue) Type

func (c *UICursorObjectValue) Type() ValueType

type UISpinnerObject

type UISpinnerObject struct{}

UISpinnerObject provides spinner control methods

type UISpinnerObjectValue

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

UISpinnerObjectValue represents gsh.ui.spinner

func (*UISpinnerObjectValue) Equals

func (s *UISpinnerObjectValue) Equals(other Value) bool

func (*UISpinnerObjectValue) GetProperty

func (s *UISpinnerObjectValue) GetProperty(name string) Value

func (*UISpinnerObjectValue) IsTruthy

func (s *UISpinnerObjectValue) IsTruthy() bool

func (*UISpinnerObjectValue) SetProperty

func (s *UISpinnerObjectValue) SetProperty(name string, value Value) error

func (*UISpinnerObjectValue) String

func (s *UISpinnerObjectValue) String() string

func (*UISpinnerObjectValue) Type

func (s *UISpinnerObjectValue) Type() ValueType

type UIStylesObject

type UIStylesObject struct{}

UIStylesObject provides semantic style functions

type UIStylesObjectValue

type UIStylesObjectValue struct{}

UIStylesObjectValue represents gsh.ui.styles

func (*UIStylesObjectValue) Equals

func (s *UIStylesObjectValue) Equals(other Value) bool

func (*UIStylesObjectValue) GetProperty

func (s *UIStylesObjectValue) GetProperty(name string) Value

func (*UIStylesObjectValue) IsTruthy

func (s *UIStylesObjectValue) IsTruthy() bool

func (*UIStylesObjectValue) SetProperty

func (s *UIStylesObjectValue) SetProperty(name string, value Value) error

func (*UIStylesObjectValue) String

func (s *UIStylesObjectValue) String() string

func (*UIStylesObjectValue) Type

func (s *UIStylesObjectValue) Type() ValueType

type Value

type Value interface {
	Type() ValueType
	String() string
	IsTruthy() bool
	Equals(other Value) bool
}

Value represents a runtime value in the interpreter

func CreateReplCommandAfterContext added in v1.2.0

func CreateReplCommandAfterContext(command string, exitCode int, durationMs int64) Value

CreateReplCommandAfterContext creates the context object for repl.command.after event ctx: { command: string, exitCode: number, durationMs: number }

func CreateReplCommandBeforeContext added in v1.2.0

func CreateReplCommandBeforeContext(command string) Value

CreateReplCommandBeforeContext creates the context object for repl.command.before event ctx: { command: string }

func CreateReplExitContext added in v1.2.0

func CreateReplExitContext() Value

CreateReplExitContext creates the context object for repl.exit event ctx: null (no context needed)

func CreateReplPredictContext added in v1.2.0

func CreateReplPredictContext(input string, trigger PredictTrigger, existingPrediction string) Value

CreateReplPredictContext creates the context object for repl.predict event ctx: { input: string, trigger: "instant" | "debounced", existingPrediction: string | null }

func CreateReplPromptContext added in v1.2.0

func CreateReplPromptContext() Value

CreateReplPromptContext creates the context object for repl.prompt event ctx: null (no context needed)

func CreateReplReadyContext added in v1.2.0

func CreateReplReadyContext() Value

CreateReplReadyContext creates the context object for repl.ready event ctx: null (no context needed)

func CreateToolEndContext

func CreateToolEndContext(name string, args map[string]interface{}, durationMs int64, success bool, err error) Value

CreateToolEndContext creates the context object for agent.tool.end event (public version)

func CreateToolStartContext

func CreateToolStartContext(name string, args map[string]interface{}) Value

CreateToolStartContext creates the context object for agent.tool.start event (public version)

func InterfaceToValue

func InterfaceToValue(val interface{}) Value

InterfaceToValue converts a Go interface{} to a Value. This is the canonical conversion function used throughout the interpreter.

func UnwrapValue

func UnwrapValue(v Value) Value

UnwrapValue unwraps a DynamicValue to its underlying value. If the value is not a DynamicValue (or doesn't implement DynamicValueGetter), it returns the original value unchanged. This should be called before type checks in operations like arithmetic, comparisons, indexing, etc.

type ValueType

type ValueType int

ValueType represents the type of a value

const (
	// ValueTypeNull represents a null value
	ValueTypeNull ValueType = iota
	// ValueTypeNumber represents a number value
	ValueTypeNumber
	// ValueTypeString represents a string value
	ValueTypeString
	// ValueTypeBool represents a boolean value
	ValueTypeBool
	// ValueTypeArray represents an array value
	ValueTypeArray
	// ValueTypeObject represents an object value
	ValueTypeObject
	// ValueTypeTool represents a tool/function value
	ValueTypeTool
	// ValueTypeError represents an error value
	ValueTypeError
	// ValueTypeModel represents a model configuration
	ValueTypeModel
	// ValueTypeAgent represents an agent configuration
	ValueTypeAgent
	// ValueTypeConversation represents a conversation state
	ValueTypeConversation
	// ValueTypeMap represents a map value
	ValueTypeMap
	// ValueTypeSet represents a set value
	ValueTypeSet
	// ValueTypeACP represents an ACP (Agent Client Protocol) agent configuration
	ValueTypeACP
	// ValueTypeACPSession represents an active ACP session
	ValueTypeACPSession
)

func (ValueType) String

func (vt ValueType) String() string

String returns the string representation of the value type

Jump to

Keyboard shortcuts

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