shell

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const MaxCallDepth = 100

MaxCallDepth is the safety limit for nested function calls to prevent infinite recursion.

View Source
const MaxLoopIterations = 10000

MaxLoopIterations is the safety limit for while loops to prevent infinite execution.

View Source
const MaxRecommendedStages = 10

MaxRecommendedStages is the soft limit on pipeline depth. Exceeding it produces a warning but does not block execution (as specified in Story 11.1 boundary cases).

Variables

This section is empty.

Functions

func SplitOnError

func SplitOnError(line string) (string, string, bool)

SplitOnError splits a line at the first unquoted "on-error" keyword. Returns (main, handler, found). Exported for CLI script syntax detection.

func StripShebang

func StripShebang(content string) string

StripShebang removes a leading shebang line (#!...) from script content. Exported for use by `rnix run` command.

Types

type ArrayLitStmt

type ArrayLitStmt struct {
	Items []string
}

ArrayLitStmt holds a parsed array literal: VAR = ["a", "b", "c"]

type BuiltinStmt

type BuiltinStmt struct {
	Command string
	Args    []string
}

BuiltinStmt holds a parsed builtin command (wait, sleep, exit).

type Command

type Command struct {
	Type   string // "spawn"
	Intent string
	Agent  string
	Model  string
}

Command represents a single parsed command in a pipeline.

type Condition

type Condition struct {
	VarName  string
	Property string // "exitcode", "result", or "" for plain variable
	Operator string // "==" or "!="
	Value    string
}

Condition represents a binary comparison: $VAR.PROP OP VALUE or $VAR OP VALUE.

type Environment

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

Environment holds shell variables for script execution. Not thread-safe — shell execution is sequential (Story 11.1).

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment creates an empty environment.

func NewEnvironmentFromOS

func NewEnvironmentFromOS() *Environment

NewEnvironmentFromOS creates an environment initialized from os.Environ().

func (*Environment) All

func (e *Environment) All() map[string]string

All returns a snapshot copy of string variables only (backward compatible).

func (*Environment) Delete

func (e *Environment) Delete(key string)

Delete removes a variable from all storage maps.

func (*Environment) Expand

func (e *Environment) Expand(input string) string

Expand performs variable substitution on input. Supports $VAR, ${VAR}, ${VAR[N]} (array index), ${VAR.KEY} (map property), and \$ escape syntax. Undefined variables expand to empty string.

func (*Environment) ExpandStrict

func (e *Environment) ExpandStrict(input string) (string, error)

ExpandStrict performs variable substitution like Expand, but returns an error when an undefined variable, out-of-bounds array index, or missing map key is referenced.

func (*Environment) Get

func (e *Environment) Get(key string) (string, bool)

Get retrieves a variable's string value.

func (*Environment) GetArray

func (e *Environment) GetArray(key string) ([]string, bool)

GetArray retrieves an array value.

func (*Environment) GetMap

func (e *Environment) GetMap(key string) (map[string]string, bool)

GetMap retrieves a map value.

func (*Environment) GetValueKind

func (e *Environment) GetValueKind(key string) string

GetValueKind returns the storage kind for a key: "string", "array", "map", or "".

func (*Environment) LenOf

func (e *Environment) LenOf(name string) (int, error)

LenOf returns the length of a variable (array length, map size, or string rune count).

func (*Environment) Set

func (e *Environment) Set(key, value string)

Set assigns a string value to a variable, clearing any array/map with the same name.

func (*Environment) SetArray

func (e *Environment) SetArray(key string, arr []string)

SetArray assigns an array value, clearing any string/map with the same name.

func (*Environment) SetMap

func (e *Environment) SetMap(key string, m map[string]string)

SetMap assigns a map value, clearing any string/array with the same name.

type ErrFnReturn

type ErrFnReturn struct {
	Value string
}

ErrFnReturn signals a function return for flow control (not a real error).

func (*ErrFnReturn) Error

func (e *ErrFnReturn) Error() string

type ErrScriptExit

type ErrScriptExit struct {
	Code int
}

ErrScriptExit signals a controlled script termination via the exit builtin.

func (*ErrScriptExit) Error

func (e *ErrScriptExit) Error() string

type ExportStmt

type ExportStmt struct {
	Key   string
	Value string
}

ExportStmt holds a parsed export KEY=VALUE.

type FileReader

type FileReader interface {
	ReadFile(path string) (string, error)
}

FileReader abstracts file reading for testability.

type FnCallStmt

type FnCallStmt struct {
	Name string
	Args []string
}

FnCallStmt holds a parsed function call: NAME(ARGS) or VAR = NAME(ARGS)

type FnDef

type FnDef struct {
	Name   string
	Params []string
	Body   []Statement
}

FnDef holds a parsed function definition: fn NAME(PARAMS) ... end

type ForBlock

type ForBlock struct {
	VarName string
	List    []string
	Body    []Statement
}

ForBlock holds a parsed for/in/end loop with variable binding and iteration list.

type IfBlock

type IfBlock struct {
	Condition Condition
	Then      []Statement
	Else      []Statement
}

IfBlock holds a parsed if/else/end block with nested statement lists.

type IndexAssign

type IndexAssign struct {
	VarName string
	Index   string
	Value   string
}

IndexAssign holds a parsed index assignment: VAR[N] = VALUE

type KernelSpawner

type KernelSpawner interface {
	SpawnAndWait(ctx context.Context, intent, agent, model string) (result string, exitCode int, tokensUsed int, err error)
	Wait(ctx context.Context, pid int) (exitCode int, err error)
}

KernelSpawner abstracts the kernel's spawn-and-wait operation for pipeline execution. Implementations bridge to the real kernel (via IPC) or mock (for testing).

type MapEntry

type MapEntry struct {
	Key   string
	Value string
}

MapEntry is a single key-value pair in a map literal.

type MapLitStmt

type MapLitStmt struct {
	Entries []MapEntry
}

MapLitStmt holds a parsed map literal: VAR = {key: "value", key2: "value2"}

type OSFileReader

type OSFileReader struct{}

OSFileReader reads files from the OS filesystem.

func (*OSFileReader) ReadFile

func (r *OSFileReader) ReadFile(path string) (string, error)

type ParallelBlock

type ParallelBlock struct {
	Body []Statement
}

ParallelBlock holds a parsed parallel/end block. Body is restricted to StmtSpawn and StmtPipeline statements only.

type Pipeline

type Pipeline struct {
	Commands []Command
}

Pipeline represents a sequence of commands connected by pipes.

func ParsePipeline

func ParsePipeline(input string) (*Pipeline, error)

ParsePipeline parses a pipeline expression like: spawn "A" | spawn "B" | spawn "C"

type PipelineExecutor

type PipelineExecutor struct {
	OnStageStart StageCallback
	// contains filtered or unexported fields
}

PipelineExecutor runs a parsed Pipeline sequentially, injecting each stage's output into the next stage's intent via [PIPE_INPUT] markers.

func NewPipelineExecutor

func NewPipelineExecutor(spawner KernelSpawner) *PipelineExecutor

NewPipelineExecutor creates a PipelineExecutor backed by the given spawner.

func (*PipelineExecutor) Execute

func (e *PipelineExecutor) Execute(ctx context.Context, pipeline *Pipeline) (*PipelineResult, error)

Execute runs each command in the pipeline sequentially. The previous stage's Result is injected as [PIPE_INPUT] into the next stage's intent. Returns an error if the spawner itself errors or context is cancelled. A non-zero ExitCode stops the pipeline but is NOT treated as an error; the partial PipelineResult is returned with stages completed so far.

type PipelineResult

type PipelineResult struct {
	Stages      []StageResult
	TotalTokens int
	Elapsed     time.Duration
}

PipelineResult holds the outcome of a pipeline execution.

type PropAssign

type PropAssign struct {
	VarName  string
	Property string
	Value    string
}

PropAssign holds a parsed property assignment: VAR.KEY = VALUE

type ReturnStmt

type ReturnStmt struct {
	Value string
}

ReturnStmt holds a parsed return statement inside a function body.

type Script

type Script struct {
	Statements []Statement
	Functions  map[string]*FnDef
}

Script is a sequence of parsed statements.

func ParseScript

func ParseScript(input string) (*Script, error)

ParseScript splits input by newlines and parses using a recursive descent parser that supports if/else/end blocks, assignment spawn, and on-error handlers.

type ScriptExecutor

type ScriptExecutor struct {
	OnStageStart StageCallback
	// contains filtered or unexported fields
}

ScriptExecutor runs a parsed Script sequentially.

func NewScriptExecutor

func NewScriptExecutor(spawner KernelSpawner, env *Environment) *ScriptExecutor

NewScriptExecutor creates a ScriptExecutor with the given spawner and environment.

func NewScriptExecutorWithReader

func NewScriptExecutorWithReader(spawner KernelSpawner, env *Environment, reader FileReader) *ScriptExecutor

NewScriptExecutorWithReader creates a ScriptExecutor with an injected FileReader.

func (*ScriptExecutor) Execute

func (e *ScriptExecutor) Execute(ctx context.Context, script *Script) (*ScriptResult, error)

Execute runs each statement in order using recursive block execution. Supports export, spawn, pipeline, if/else/end, assignment spawn, and on-error.

func (*ScriptExecutor) SetFileReader

func (e *ScriptExecutor) SetFileReader(r FileReader)

SetFileReader sets the file reader implementation.

func (*ScriptExecutor) SetScriptDir

func (e *ScriptExecutor) SetScriptDir(dir string)

SetScriptDir sets the base directory for resolving relative source paths.

type ScriptResult

type ScriptResult struct {
	LastResult   string
	LastExitCode int
	TotalTokens  int
	Elapsed      time.Duration
}

ScriptResult holds the outcome of a script execution.

type SourceStmt

type SourceStmt struct {
	Path string // source target file path (raw value, may contain variables)
}

SourceStmt holds a parsed source statement: source <path>

type SpawnResult

type SpawnResult struct {
	ExitCode int
	Result   string
	Tokens   int
}

SpawnResult captures the outcome of an assignment spawn for condition evaluation.

type StageCallback

type StageCallback func(stage, total int, intent string)

StageCallback is invoked when a pipeline stage begins execution.

type StageResult

type StageResult struct {
	PID        int
	Intent     string
	Result     string
	ExitCode   int
	TokensUsed int
	Elapsed    time.Duration
}

StageResult holds the outcome of a single pipeline stage.

type Statement

type Statement struct {
	Kind        StatementKind
	Export      *ExportStmt
	Spawn       *Command
	Pipeline    *Pipeline
	If          *IfBlock
	For         *ForBlock
	While       *WhileBlock
	Parallel    *ParallelBlock
	Source      *SourceStmt
	Builtin     *BuiltinStmt
	FnDef       *FnDef
	FnCall      *FnCallStmt
	Return      *ReturnStmt
	ArrayLit    *ArrayLitStmt
	MapLit      *MapLitStmt
	IndexAssign *IndexAssign
	PropAssign  *PropAssign
	Assign      string   // variable name for assignment spawn/fn-call/array-lit/map-lit
	OnError     *Command // on-error handler spawn command
	Raw         string
	Line        int // 1-based line number from source
}

Statement is a single parsed line of a script.

type StatementKind

type StatementKind string

StatementKind identifies the type of a parsed statement.

const (
	StmtExport      StatementKind = "export"
	StmtSpawn       StatementKind = "spawn"
	StmtPipeline    StatementKind = "pipeline"
	StmtIf          StatementKind = "if"
	StmtFor         StatementKind = "for"
	StmtWhile       StatementKind = "while"
	StmtBuiltin     StatementKind = "builtin"
	StmtFnDef       StatementKind = "fn-def"
	StmtFnCall      StatementKind = "fn-call"
	StmtReturn      StatementKind = "return"
	StmtArrayLit    StatementKind = "array-lit"
	StmtMapLit      StatementKind = "map-lit"
	StmtAssignIndex StatementKind = "assign-index"
	StmtAssignProp  StatementKind = "assign-prop"
	StmtParallel    StatementKind = "parallel"
	StmtSource      StatementKind = "source"
)

type WhileBlock

type WhileBlock struct {
	Condition Condition
	Body      []Statement
}

WhileBlock holds a parsed while/end loop with a condition.

Jump to

Keyboard shortcuts

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