sandbox

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package sandbox executes compiled TypeScript programs inside isolated goja JavaScript VMs with concurrent host Promise bridging, operation budgets, and deadline enforcement.

Index

Constants

View Source
const (
	DefaultTimeout = 20 * time.Second
	MaxTimeout     = 120 * time.Second
	DefaultMaxOps  = 400
	MaxLogEntries  = 2000
	MaxLogBytes    = 256 * 1024
)
View Source
const (
	KindNotFound      = "NotFound"      // path does not exist
	KindNoMatch       = "NoMatch"       // edit target not found
	KindAmbiguous     = "Ambiguous"     // edit target matches several places
	KindNeedsApproval = "NeedsApproval" // policy requires the user's confirmation via a native tool
	KindDenied        = "Denied"        // policy forbids the operation
	KindTimeout       = "Timeout"
	KindBadArgs       = "BadArgs"
	KindCmdFailed     = "CmdFailed" // command exited non-zero with throwOnError
	KindError         = "Error"     // anything else
)

Error kinds exposed to guest JS as `e.name`. Short, semantic, and stable so programs can branch on them.

View Source
const MaxCallStackDepth = 8192

MaxCallStackDepth bounds JS call depth (roughly Node's default ~10k frames) so runaway recursion fails in milliseconds with bounded memory instead of running until the exec timeout. Async functions consume about two frames per level, so ~4k levels of async recursion still work.

Variables

This section is empty.

Functions

func EffectiveDefaultTimeout

func EffectiveDefaultTimeout() time.Duration

EffectiveDefaultTimeout returns DefaultTimeout (20s) unless overridden via AGY_PTC_DEFAULT_TIMEOUT_MS.

func EffectiveMaxTimeout

func EffectiveMaxTimeout() time.Duration

EffectiveMaxTimeout returns MaxTimeout (120s) unless overridden via AGY_PTC_MAX_TIMEOUT_MS.

func IsSideEffectOp

func IsSideEffectOp(op string) bool

IsSideEffectOp reports whether a (public) op name may have changed state outside the sandbox.

func PublicOpName

func PublicOpName(capability string) string

PublicOpName hides internal raw methods: `tx._begin` -> `tx.begin`, `tx._edit` -> `t.edit` (the handle the user holds). Other raw `ns._m` helpers wrapped by the bootstrap (e.g. fs._bytes) surface as `ns.m`.

Types

type AsyncHostFunc

type AsyncHostFunc func(ctx context.Context, args []any) (any, error)

AsyncHostFunc is a thread-safe Go function invoked asynchronously from guest JS. Arguments have already been exported on the VM thread before running in a goroutine.

type Binder

type Binder interface {
	Bind(env *ExecutionEnv) error
}

Binder allows capability packages to register namespaces onto an ExecutionEnv.

type ExecRequest

type ExecRequest struct {
	Title     string
	Code      string
	Payloads  map[string]string
	Cwd       string
	Timeout   time.Duration
	MaxOps    int
	OnOpStart func(capability, target string, seq int)
}

ExecRequest describes a single PTC program invocation.

type ExecResult

type ExecResult struct {
	Value      any       `json:"value"`
	HasValue   bool      `json:"hasValue,omitempty"`
	Logs       []string  `json:"logs,omitempty"`
	Warnings   []string  `json:"warnings,omitempty"`
	Traces     []OpTrace `json:"traces,omitempty"`
	DurationMs int64     `json:"durationMs"`
}

ExecResult contains the outcome, logs, and operation trace of a PTC execution.

func Execute

func Execute(parentCtx context.Context, req ExecRequest, binders ...Binder) (result *ExecResult, retErr error)

Execute compiles TypeScript code, boots a fresh isolated goja VM, binds capabilities, and awaits completion.

type ExecutionEnv

type ExecutionEnv struct {
	ExecID string
	Ctx    context.Context
	Cwd    string
	VM     *goja.Runtime
	// contains filtered or unexported fields
}

ExecutionEnv represents one isolated VM run and provides safe host binding helpers.

func (*ExecutionEnv) AddWarning

func (env *ExecutionEnv) AddWarning(msg string)

AddWarning records a host-side notice that must reach the model even when the program succeeded (e.g. an uncommitted transaction was auto-rolled back, or a rollback could not restore a file). Identical messages are collapsed into one line with a `(×N)` suffix.

func (*ExecutionEnv) RegisterCleanup

func (env *ExecutionEnv) RegisterCleanup(fn func())

RegisterCleanup registers a function to run when the VM execution finishes (e.g. rolling back uncommitted transactions). Cleanup functions may call AddWarning; warnings are attached to the returned ExecResult / ExecutionError.

func (*ExecutionEnv) SetNamespace

func (env *ExecutionEnv) SetNamespace(ns string, asyncMethods map[string]AsyncHostFunc, syncMethods map[string]SyncHostFunc) error

SetNamespace creates or replaces a global object with the given async and sync methods.

type ExecutionError

type ExecutionError struct {
	Phase       string // "compile" | "runtime" | "timeout"
	Message     string
	TimedOutOps []string
	Logs        []string
	Warnings    []string
	Traces      []OpTrace
	DurationMs  int64
}

ExecutionError wraps compile or runtime failures along with partial logs and completed traces.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

type HostError

type HostError struct {
	Kind string
	Msg  string
	Data map[string]any
}

HostError is a capability failure carrying a semantic kind and optional structured data (exposed as `e.data`).

func NewHostError

func NewHostError(kind string, data map[string]any, format string, args ...any) *HostError

NewHostError builds a HostError with a formatted message.

func (*HostError) Error

func (e *HostError) Error() string

type KindedError

type KindedError interface {
	error
	Kind() string
	Detail() string
}

KindedError lets errors from other packages (e.g. policy.PolicyError) declare their kind without importing sandbox. Detail is the message without the kind word, so `name: op: detail` never repeats itself.

type OpTrace

type OpTrace struct {
	Seq        int    `json:"seq"`
	Wave       int    `json:"wave,omitempty"` // parallel execution wave ID; ops sharing a Wave overlapped in flight (e.g. Promise.all)
	Capability string `json:"capability"`
	Target     string `json:"target,omitempty"`
	StartMs    int64  `json:"startMs,omitempty"` // offset in ms from exec start
	DurationMs int64  `json:"durationMs"`
	Status     string `json:"status"` // "ok" | "error"
	Kind       string `json:"kind,omitempty"`
	Error      string `json:"error,omitempty"`
	Bytes      int    `json:"bytes,omitempty"` // approximate size of the result handed to the program
}

OpTrace records a single host capability call executed by a guest program.

type OrderedMap

type OrderedMap struct {
	Keys []string
	Vals []any
}

OrderedMap is returned by host functions that must preserve key order in the guest object (Go maps iterate randomly). Keys and Vals are parallel slices.

type SyncHostFunc

type SyncHostFunc func(ctx context.Context, args []any) (any, error)

SyncHostFunc runs synchronously on the VM thread.

Jump to

Keyboard shortcuts

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