codeexecutor

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 16 Imported by: 6

Documentation

Overview

Package codeexecutor provides an interface and utilities for executing code blocks and running programs in workspaces.

Package codeexecutor holds workspace metadata helpers and constants.

Package codeexecutor defines workspace types and helpers.

Index

Constants

View Source
const (
	// ProgramStatusRunning indicates the interactive program is still
	// running and may accept more input.
	ProgramStatusRunning = "running"
	// ProgramStatusExited indicates the interactive program has exited.
	ProgramStatusExited = "exited"
)
View Source
const (
	// DirSkills contains session-scoped skill working copies. Skills
	// staged here are writable by default so third-party scripts can
	// emit cache files, temporary outputs, and Python bytecode next to
	// their source. Callers that need a stable, canonical skill tree
	// should treat the upstream skill repository as the source of
	// truth; the copy under this directory is a working copy tied to
	// the current session.
	DirSkills = "skills"
	// DirWork contains writable shared intermediates.
	DirWork = "work"
	// DirRuns contains per-run working directories.
	DirRuns = "runs"
	// DirOut contains collected outputs for artifacting.
	DirOut = "out"
	// MetaFileName is the metadata file name at workspace root.
	MetaFileName = "metadata.json"
)

Well-known subdirectories in a workspace.

View Source
const (
	EnvSkillsDir = "SKILLS_DIR"
	EnvWorkDir   = "WORK_DIR"
	EnvOutputDir = "OUTPUT_DIR"
	EnvRunDir    = "RUN_DIR"
	EnvSkillName = "SKILL_NAME"
)

Additional environment variable keys injected at runtime.

View Source
const (
	// WorkspaceEnvDirKey is set in program env to point to the workspace
	// directory for outputs and scratch files.
	WorkspaceEnvDirKey = "WORKSPACE_DIR"

	// Span names for workspace lifecycle.
	SpanWorkspaceCreate     = "workspace.create"
	SpanWorkspaceCleanup    = "workspace.cleanup"
	SpanWorkspaceStageFiles = "workspace.stage.files"
	SpanWorkspaceStageDir   = "workspace.stage.dir"
	SpanWorkspaceRun        = "workspace.run"
	SpanWorkspaceCollect    = "workspace.collect"
	SpanWorkspaceInline     = "workspace.inline"

	// Common attribute keys used in tracing spans.
	AttrExecID    = "exec_id"
	AttrPath      = "path"
	AttrCount     = "count"
	AttrPatterns  = "patterns"
	AttrCmd       = "cmd"
	AttrCwd       = "cwd"
	AttrExitCode  = "exit_code"
	AttrTimedOut  = "timed_out"
	AttrHostPath  = "host_path"
	AttrTo        = "to"
	AttrMountUsed = "mount_used"
)

Well-known environment and telemetry keys to avoid magic strings.

View Source
const (
	// DefaultScriptFileMode is the default POSIX mode for text scripts.
	DefaultScriptFileMode = 0o644
	// DefaultExecFileMode is the default POSIX mode for executables.
	DefaultExecFileMode = 0o755
	// InlineSourceDir is the subdirectory where inline code blocks
	// are written and executed as the current working directory.
	InlineSourceDir = "src"
)

Default file modes and common subdirectories.

Variables

View Source
var ErrWorkspaceInitIncompleteEngine = errors.New(
	"codeexecutor: Engine() or Engine.Manager() is nil",
)

ErrWorkspaceInitIncompleteEngine is returned when Engine() or Manager() is nil.

View Source
var ErrWorkspaceInitNeedsEngineProvider = errors.New(
	"codeexecutor: workspace init hooks require CodeExecutor to implement EngineProvider",
)

ErrWorkspaceInitNeedsEngineProvider is returned when hooks are requested but the executor does not implement EngineProvider.

Functions

func ArtifactServiceFromContext added in v0.5.0

func ArtifactServiceFromContext(
	ctx context.Context,
) (artifact.Service, bool)

ArtifactServiceFromContext fetches the artifact.Service previously stored by WithArtifactService. It returns the service and a boolean indicating presence.

func BuildBlockSpec added in v0.5.0

func BuildBlockSpec(
	idx int,
	b CodeBlock,
) (file string, mode uint32, cmd string, args []string, err error)

BuildBlockSpec maps a code block into a file name, mode, command, and arguments suitable for execution via RunProgram. It supports a minimal set of languages to keep behavior predictable.

func DirDigest added in v0.5.0

func DirDigest(root string) (string, error)

DirDigest computes a stable digest of a directory tree. It walks the tree, sorts entries, and hashes relative path and contents.

func EnsureLayout added in v0.5.0

func EnsureLayout(root string) (map[string]string, error)

EnsureLayout creates standard workspace subdirectories and a metadata file when absent. It returns full paths for convenience.

func IsTextMIME added in v1.3.0

func IsTextMIME(mimeType string) bool

IsTextMIME reports whether mimeType describes a text format that is safe to inline as UTF-8 text.

func LoadArtifactHelper added in v0.5.0

func LoadArtifactHelper(
	ctx context.Context, name string, version *int,
) ([]byte, string, int, error)

LoadArtifactHelper resolves artifact name@version via callback context. If version is nil, loads latest. Returns data, mime, actual version.

func NormalizeGlobs added in v0.6.0

func NormalizeGlobs(patterns []string) []string

NormalizeGlobs rewrites glob patterns that use well-known environment-style prefixes such as $OUTPUT_DIR into workspace- relative paths like out/. It understands the variables injected by workspace runtimes: WORKSPACE_DIR, SKILLS_DIR, WORK_DIR, OUTPUT_DIR.

Examples:

$OUTPUT_DIR/a.txt   -> out/a.txt
${WORK_DIR}/x/**    -> work/x/**
$WORKSPACE_DIR/out  -> out

Unknown variables and patterns without a prefix are returned as-is.

func ParseArtifactRef added in v0.5.0

func ParseArtifactRef(ref string) (string, *int, error)

ParseArtifactRef splits "name@version" into name and optional version.

func SaveArtifactHelper added in v0.5.0

func SaveArtifactHelper(
	ctx context.Context, filename string, data []byte, mime string,
) (int, error)

SaveArtifactHelper saves a file as artifact using callback context.

func SaveMetadata added in v0.5.0

func SaveMetadata(root string, md WorkspaceMetadata) error

SaveMetadata writes metadata.json to the workspace root.

func WithArtifactService added in v0.5.0

func WithArtifactService(
	ctx context.Context, svc artifact.Service,
) context.Context

WithArtifactService stores an artifact.Service in the context. Callers retrieve it in lower layers to load/save artifacts without importing higher-level packages.

func WithArtifactSession added in v0.5.0

func WithArtifactSession(
	ctx context.Context, info artifact.SessionInfo,
) context.Context

WithArtifactSession stores artifact session info in context.

Types

type Capabilities added in v0.5.0

type Capabilities struct {
	Isolation      string
	NetworkAllowed bool
	ReadOnlyMount  bool
	Streaming      bool
	MaxDiskBytes   int64
}

Capabilities describes engine capabilities for selection.

type CodeBlock

type CodeBlock struct {
	Code     string `json:"code"`
	Language string `json:"language"`
}

CodeBlock represents a single block of code to be executed.

func ExtractCodeBlock

func ExtractCodeBlock(
	input string,
	delimiter CodeBlockDelimiter,
) []CodeBlock

ExtractCodeBlock extracts fenced code blocks using the given delimiter.

type CodeBlockDelimiter

type CodeBlockDelimiter struct {
	Start string
	End   string
}

CodeBlockDelimiter defines the start and end delimiters for code blocks.

type CodeExecutionInput

type CodeExecutionInput struct {
	CodeBlocks  []CodeBlock `json:"code_blocks"`
	ExecutionID string      `json:"execution_id,omitempty"`
}

CodeExecutionInput is the input for code execution.

type CodeExecutionResult

type CodeExecutionResult struct {
	Output      string `json:"output"`
	OutputFiles []File `json:"output_files,omitempty"`
}

CodeExecutionResult is the result of code execution including files.

func (CodeExecutionResult) String

func (r CodeExecutionResult) String() string

String formats a human-readable result.

type CodeExecutor

type CodeExecutor interface {
	// ExecuteCode executes the code blocks provided in the input and
	// returns the result.
	ExecuteCode(context.Context, CodeExecutionInput) (CodeExecutionResult, error)
	// CodeBlockDelimiter returns the delimiters used for code blocks.
	CodeBlockDelimiter() CodeBlockDelimiter
}

CodeExecutor executes code blocks via a friendly front-door API.

func NewEnvInjectingCodeExecutor added in v1.8.0

func NewEnvInjectingCodeExecutor(
	exec CodeExecutor,
	provider RunEnvProvider,
) CodeExecutor

NewEnvInjectingCodeExecutor wraps exec so that Engine() returns an env-injecting engine. exec must implement EngineProvider; if it does not (or is nil), the original executor is returned unchanged.

This is the recommended top-level entry point: pass the wrapped executor to llmagent.WithCodeExecutor and all tool paths (skill_run, workspace_exec, interactive sessions) will automatically receive the injected environment variables.

func NewWorkspaceInitExecutor added in v1.9.0

func NewWorkspaceInitExecutor(
	exec CodeExecutor,
	hooks ...WorkspaceInitHook,
) (CodeExecutor, error)

NewWorkspaceInitExecutor wraps exec so every [WorkspaceManager.CreateWorkspace] runs the given hooks before returning the workspace.

When hooks is non-empty, exec must implement EngineProvider with a non-nil Engine and non-nil WorkspaceManager; otherwise this function returns an error satisfying ErrWorkspaceInitNeedsEngineProvider or ErrWorkspaceInitIncompleteEngine.

For InputSpec values that use artifact://, the context passed to CreateWorkspace must carry the artifact service and (when applicable) session information—the same requirements as [WorkspaceFS.StageInputs]. Standard agent workspace-session tooling injects that context before WorkspaceRegistry.Acquire, so init hooks can load artifacts without extra setup.

type Engine added in v0.5.0

type Engine interface {
	Manager() WorkspaceManager
	FS() WorkspaceFS
	Runner() ProgramRunner
	// Describe returns optional capabilities.
	Describe() Capabilities
}

Engine is a backend that provides workspace and execution services.

func NewEngine added in v0.5.0

func NewEngine(
	m WorkspaceManager,
	f WorkspaceFS,
	r ProgramRunner,
) Engine

NewEngine constructs a simple Engine from its components.

func NewEnvInjectingEngine added in v1.8.0

func NewEnvInjectingEngine(eng Engine, provider RunEnvProvider) Engine

NewEnvInjectingEngine wraps eng so that every RunProgram and StartProgram call merges environment variables from provider into the spec before delegating to the underlying runner.

If eng or provider is nil the original engine is returned unchanged.

type EngineProvider added in v0.5.0

type EngineProvider interface {
	Engine() Engine
}

EngineProvider is an optional interface that a CodeExecutor may implement to expose its underlying engine for skill tools.

type File

type File struct {
	Name      string `json:"name"`
	Content   string `json:"content,omitempty"`
	MIMEType  string `json:"mime_type"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	Truncated bool   `json:"truncated,omitempty"`
}

File represents a file generated during code execution.

type FileRef added in v0.5.0

type FileRef struct {
	Name      string
	MIMEType  string
	Content   string
	SavedAs   string
	Version   int
	SizeBytes int64
	Truncated bool
}

FileRef references a file collected from workspace.

type InputRecord added in v0.5.0

type InputRecord struct {
	From      string    `json:"from"`
	To        string    `json:"to"`
	Resolved  string    `json:"resolved,omitempty"`
	Version   *int      `json:"version,omitempty"`
	Mode      string    `json:"mode,omitempty"`
	Timestamp time.Time `json:"ts"`
}

InputRecord tracks a staged input resolution.

type InputSpec added in v0.5.0

type InputSpec struct {
	From string
	To   string
	Mode string
	Pin  bool
}

InputSpec declares a single input mapping into the workspace.

From supports schemes:

  • artifact://name[@version]
  • host://abs/path
  • workspace://rel/path
  • skill://name/rel/path

To is a workspace-relative destination (default: WORK_DIR/inputs/<name>). Mode hints the strategy: "link" (symlink/hardlink where possible) or "copy" (default fallback when link is not possible).

type InteractiveProgramRunner added in v1.7.0

type InteractiveProgramRunner interface {
	StartProgram(
		ctx context.Context,
		ws Workspace,
		spec InteractiveProgramSpec,
	) (ProgramSession, error)
}

InteractiveProgramRunner is an optional executor capability for multi-turn interactive program execution.

type InteractiveProgramSpec added in v1.7.0

type InteractiveProgramSpec struct {
	RunProgramSpec
	TTY bool
}

InteractiveProgramSpec describes a session-oriented program invocation in a workspace.

type OutputManifest added in v0.5.0

type OutputManifest struct {
	Files     []FileRef
	LimitsHit bool
}

OutputManifest is the structured result of CollectOutputs.

type OutputRecord added in v0.5.0

type OutputRecord struct {
	Globs     []string  `json:"globs"`
	SavedAs   []string  `json:"saved_as,omitempty"`
	Versions  []int     `json:"versions,omitempty"`
	LimitsHit bool      `json:"limits_hit"`
	Timestamp time.Time `json:"ts"`
}

OutputRecord tracks an output collection run.

type OutputSpec added in v0.5.0

type OutputSpec struct {
	Globs         []string
	MaxFiles      int
	MaxFileBytes  int64
	MaxTotalBytes int64
	Save          bool
	NameTemplate  string
	Inline        bool
}

OutputSpec declares outputs to collect and optionally persist. Globs are workspace-relative patterns; implementations should support ** semantics.

func (*OutputSpec) UnmarshalJSON added in v1.3.0

func (s *OutputSpec) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both legacy Go-style keys (MaxFiles) and the recommended snake_case keys (max_files).

type PreparedRecord added in v1.9.0

type PreparedRecord struct {
	Key         string    `json:"key"`
	Kind        string    `json:"kind"`
	Fingerprint string    `json:"fingerprint"`
	Target      string    `json:"target,omitempty"`
	PreparedAt  time.Time `json:"prepared_at"`
}

PreparedRecord captures a single successfully-applied workspace requirement. It is written by the reconciler after a successful apply and read on subsequent reconciles to decide whether to skip.

type ProgramLog added in v1.7.0

type ProgramLog struct {
	Output     string
	Offset     int
	NextOffset int
}

ProgramLog returns output from a specific offset without mutating the incremental cursor.

type ProgramPoll added in v1.7.0

type ProgramPoll struct {
	Status     string
	Output     string
	Offset     int
	NextOffset int
	ExitCode   *int
}

ProgramPoll captures the latest incremental output for a running or exited interactive program session.

type ProgramResultProvider added in v1.7.0

type ProgramResultProvider interface {
	RunResult() RunResult
}

ProgramResultProvider optionally exposes a final RunResult for interactive sessions after they exit.

type ProgramRunner added in v0.5.0

type ProgramRunner interface {
	RunProgram(ctx context.Context, ws Workspace,
		spec RunProgramSpec) (RunResult, error)
}

ProgramRunner executes programs within a workspace.

type ProgramSession added in v1.7.0

type ProgramSession interface {
	ID() string
	Poll(limit *int) ProgramPoll
	Log(offset *int, limit *int) ProgramLog
	Write(data string, newline bool) error
	Kill(grace time.Duration) error
	Close() error
}

ProgramSession exposes a running interactive program session.

Implementations are expected to be safe for concurrent use by tool-layer callers. In particular, Poll, Log, Write, Kill, Close, and any optional state/result helpers may be invoked concurrently for the same session.

type ProgramState added in v1.8.0

type ProgramState struct {
	Status   string
	ExitCode *int
}

ProgramState captures non-streaming session status without advancing any incremental output cursor.

type ProgramStateProvider added in v1.8.0

type ProgramStateProvider interface {
	State() ProgramState
}

ProgramStateProvider optionally exposes non-destructive session state for lifecycle management and cleanup.

type PutFile added in v0.5.0

type PutFile struct {
	Path    string // relative to workspace root
	Content []byte
	Mode    uint32 // POSIX mode bits (e.g., 0644, 0755)
}

PutFile describes a file to place into a workspace.

type ResourceLimits added in v0.5.0

type ResourceLimits struct {
	// CPUPercent is an approximate percentage of one CPU.
	CPUPercent int
	// MemoryMB is a soft limit in megabytes.
	MemoryMB int
	// MaxPIDs limits number of processes/threads.
	MaxPIDs int
}

ResourceLimits restrict program execution resources.

type RunEnvProvider added in v1.8.0

type RunEnvProvider func(ctx context.Context) map[string]string

RunEnvProvider returns per-run environment variables derived from the execution context. Implementations typically read caller-supplied state (e.g. user tokens) from the context and return them as key-value pairs to be merged into every RunProgramSpec executed by the wrapped engine.

Returned entries never override values already present in the spec's Env map, preserving explicit per-call overrides from tools.

type RunProgramSpec added in v0.5.0

type RunProgramSpec struct {
	Cmd     string
	Args    []string
	Env     map[string]string
	Cwd     string // relative to workspace root
	Stdin   string
	Timeout time.Duration
	Limits  ResourceLimits
}

RunProgramSpec describes a program invocation in a workspace.

type RunResult added in v0.5.0

type RunResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
	Duration time.Duration
	TimedOut bool
}

RunResult captures a single program run result.

type SkillMeta added in v0.5.0

type SkillMeta struct {
	Name     string    `json:"name"`
	RelPath  string    `json:"rel_path"`
	Digest   string    `json:"digest"`
	Mounted  bool      `json:"mounted"`
	StagedAt time.Time `json:"staged_at"`
}

SkillMeta records a staged skill snapshot.

type StageOptions added in v0.5.0

type StageOptions struct {
	// ReadOnly makes the staged tree non-writable after copy/mount.
	ReadOnly bool
	// AllowMount lets implementations use read-only mounts when possible.
	AllowMount bool
}

StageOptions controls directory staging behavior.

type Workspace added in v0.5.0

type Workspace struct {
	ID   string
	Path string
}

Workspace represents an isolated execution workspace. Path is host path for local runtime or a logical mount path for containers.

type WorkspaceBootstrapSpec added in v1.9.0

type WorkspaceBootstrapSpec struct {
	// Files are static inputs that must exist before commands run.
	// Each entry maps a workspace-relative Target to either inline
	// Content or a richer Input source (artifact://, host://,
	// workspace://, skill://).
	Files []WorkspaceFile
	// Commands are one-shot initialization commands such as
	// "python3 -m venv .venv" or "pip install -r requirements.txt".
	Commands []WorkspaceCommand
}

WorkspaceBootstrapSpec is the user-facing description of "what must exist in the workspace before any user command runs". It is intentionally narrow: the framework's reconciler abstractions (Requirement / Provider / Reconciler) are not part of the public API while their semantics are still being refined. Business code composes WorkspaceFile and WorkspaceCommand declaratively, and the agent translates them into reconcile work behind the scenes.

The spec is independent of any particular agent type: it describes workspace state, not agent behavior. Agent packages (for example llmagent) provide Options that accept a WorkspaceBootstrapSpec and wire it into their workspace_exec tool.

Files are staged first (in declaration order); Commands then run (also in declaration order). Both are idempotent: the reconciler fingerprints each entry and skips work whose fingerprint plus on-disk sentinel are still satisfied.

type WorkspaceCommand added in v1.9.0

type WorkspaceCommand struct {
	// Key is an optional stable identifier. When empty the
	// reconciler derives one from Cmd+Args.
	Key string
	// Cmd is the program to execute.
	Cmd string
	// Args are command-line arguments passed verbatim.
	Args []string
	// Env augments the run environment.
	Env map[string]string
	// Cwd is a workspace-relative working directory.
	Cwd string
	// Timeout bounds a single run. Zero means no extra timeout
	// beyond the engine's default.
	Timeout time.Duration
	// MarkerPath is a workspace-relative sentinel file. When set
	// and missing, Apply creates it after a successful run.
	MarkerPath string
	// ObservedPaths are additional workspace-relative paths used
	// as sentinels for self-healing.
	ObservedPaths []string
	// FingerprintInputs are workspace-relative files whose
	// contents are hashed into Fingerprint.
	FingerprintInputs []string
	// FingerprintSalt is a caller-supplied version string added
	// to the fingerprint, letting business config force a re-run
	// without changing Cmd/Args.
	FingerprintSalt string
	// Optional marks this command as non-blocking: failures are
	// surfaced as warnings instead of aborting the workspace.
	Optional bool
}

WorkspaceCommand describes a one-shot command the framework must execute during workspace preparation. The command runs through the engine's runner, with the same isolation guarantees as user commands.

Self-healing notes:

  • When MarkerPath is set, the reconciler treats the marker as the sentinel: removing it forces the command to re-run on the next reconcile.
  • When ObservedPaths is set, the sentinel is satisfied only if all listed paths still exist.
  • When neither is set, re-runs are driven purely by Fingerprint changes (Cmd/Args/Env/Cwd/FingerprintInputs/FingerprintSalt).

FingerprintInputs lets callers fold the contents of arbitrary workspace-relative files into the fingerprint so that edits to, for example, requirements.txt naturally force a re-install.

type WorkspaceFS added in v0.5.0

type WorkspaceFS interface {
	PutFiles(ctx context.Context, ws Workspace,
		files []PutFile) error
	StageDirectory(ctx context.Context, ws Workspace,
		src, to string, opt StageOptions) error
	Collect(ctx context.Context, ws Workspace,
		patterns []string) ([]File, error)
	// StageInputs maps external inputs into workspace according to
	// the provided specs. Implementations should prefer link
	// strategies when Mode=="link" and environment allows it.
	StageInputs(ctx context.Context, ws Workspace,
		specs []InputSpec) error
	// CollectOutputs applies the declarative output spec to collect
	// files and optionally persist artifacts.
	CollectOutputs(ctx context.Context, ws Workspace,
		spec OutputSpec) (OutputManifest, error)
}

WorkspaceFS performs file operations within a workspace.

type WorkspaceFile added in v1.9.0

type WorkspaceFile struct {
	// Key is an optional stable identifier. When empty the
	// reconciler derives one from Target.
	Key string
	// Target is the workspace-relative destination path.
	Target string
	// Content is inline file content. When set, Input is ignored.
	Content []byte
	// Mode is the POSIX mode for inline writes. When zero, inline
	// writes fall back to DefaultScriptFileMode (0o644).
	Mode uint32
	// Input is a richer source spec covering artifact://, host://,
	// workspace://, and skill:// URIs.
	Input *InputSpec
	// Optional marks this file as non-blocking: failures are
	// surfaced as warnings instead of aborting the workspace.
	Optional bool
}

WorkspaceFile describes a single file the framework must stage into the workspace before user commands run. Exactly one of Content or Input should be set.

type WorkspaceInitCommand added in v1.9.0

type WorkspaceInitCommand struct {
	Name    string
	Cmd     string
	Args    []string
	Env     map[string]string
	Cwd     string
	Stdin   string
	Timeout time.Duration
}

WorkspaceInitCommand describes one init-time program run. Fields align with RunProgramSpec minus ResourceLimits, which init hooks omit in v1. Name is optional; when set it appears in errors for that command.

type WorkspaceInitEnv added in v1.9.0

type WorkspaceInitEnv struct {
	Workspace    Workspace
	ExecID       string
	Policy       WorkspacePolicy
	FS           WorkspaceFS
	Runner       ProgramRunner
	Capabilities Capabilities
}

WorkspaceInitEnv is the capability bundle passed to each WorkspaceInitHook. The workspace directory already exists when the hook runs.

type WorkspaceInitHook added in v1.9.0

type WorkspaceInitHook func(context.Context, WorkspaceInitEnv) error

WorkspaceInitHook is a callback run after [WorkspaceManager.CreateWorkspace] succeeds and before that workspace is returned to callers. Use it for deterministic setup (stage inputs, install dependencies). Hooks are scoped to workspace creation: they do not watch files on disk or re-run later solely because workspace contents changed.

Multiple hooks run in declaration order; failure labels use hook index (0, 1, ...). Use NewWorkspaceInitHook for declarative staging and commands with per-command diagnostic names in errors.

func NewWorkspaceInitHook added in v1.9.0

func NewWorkspaceInitHook(spec WorkspaceInitSpec) WorkspaceInitHook

NewWorkspaceInitHook wraps WorkspaceInitSpec as a WorkspaceInitHook function.

type WorkspaceInitSpec added in v1.9.0

type WorkspaceInitSpec struct {
	// Inputs are staged via [WorkspaceFS.StageInputs] (artifact://, host://, etc.).
	Inputs []InputSpec
	// Commands run sequentially after inputs; non-zero exit code fails the hook.
	Commands []WorkspaceInitCommand
}

WorkspaceInitSpec is a declarative hook: stage InputSpec inputs, then run init commands in order. It does not express per-tool-call idempotency; callers that need convergence on every tool invocation handle that at a higher layer.

type WorkspaceManager added in v0.5.0

type WorkspaceManager interface {
	CreateWorkspace(ctx context.Context, execID string,
		pol WorkspacePolicy) (Workspace, error)
	Cleanup(ctx context.Context, ws Workspace) error
}

WorkspaceManager handles workspace lifecycle.

type WorkspaceMetadata added in v0.5.0

type WorkspaceMetadata struct {
	Version    int                  `json:"version"`
	CreatedAt  time.Time            `json:"created_at"`
	UpdatedAt  time.Time            `json:"updated_at"`
	LastAccess time.Time            `json:"last_access"`
	Skills     map[string]SkillMeta `json:"skills"`
	Inputs     []InputRecord        `json:"inputs,omitempty"`
	Outputs    []OutputRecord       `json:"outputs,omitempty"`
	// Prepared records the last-known converged state for each
	// workspace requirement keyed by Requirement.Key(). It is used by
	// the workspaceprep reconciler to skip work whose fingerprint is
	// unchanged and whose sentinel (for example the target file) is
	// still present. The map is a local per-workspace cache; session
	// state remains the authoritative source of "what should exist".
	Prepared map[string]PreparedRecord `json:"prepared,omitempty"`
}

WorkspaceMetadata describes staged skills and recent activity.

func LoadMetadata added in v0.5.0

func LoadMetadata(root string) (WorkspaceMetadata, error)

LoadMetadata loads metadata.json from workspace root. When missing, an empty metadata with defaults is returned without error.

type WorkspacePolicy added in v0.5.0

type WorkspacePolicy struct {
	// Isolated toggles runtime isolation (e.g., container usage).
	Isolated bool
	// Persist keeps workspace after Cleanup when true.
	Persist bool
	// MaxDiskBytes is a soft limit for staged and produced files.
	MaxDiskBytes int64
}

WorkspacePolicy configures workspace behavior.

type WorkspaceRegistry added in v0.5.0

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

WorkspaceRegistry keeps a process-level mapping of logical IDs to created workspaces for reuse within a session.

func NewWorkspaceRegistry added in v0.5.0

func NewWorkspaceRegistry() *WorkspaceRegistry

NewWorkspaceRegistry creates a new in-memory registry.

func (*WorkspaceRegistry) Acquire added in v0.5.0

Acquire creates or returns an existing workspace with the given id. Concurrent first-time acquires for the same id coalesce to a single CreateWorkspace so init hooks and workspace creation run at most once per id.

Directories

Path Synopsis
container module
e2b
Package e2b provides a CodeExecutor implementation for E2B.
Package e2b provides a CodeExecutor implementation for E2B.
internal/codeinterpreter
Package codeinterpreter provides a CodeInterpreter implementation for E2B.
Package codeinterpreter provides a CodeInterpreter implementation for E2B.
internal/codeinterpreter/example command
Example command demonstrating typical use of the Go Code Interpreter SDK.
Example command demonstrating typical use of the Go Code Interpreter SDK.
jupyter module
Package local provides a CodeExecutor that executes code blocks in the local environment.
Package local provides a CodeExecutor that executes code blocks in the local environment.

Jump to

Keyboard shortcuts

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