jsruntime

package
v0.22.1-rc.8 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SupportedLanguages = []string{"javascript", "typescript"}

SupportedLanguages lists all valid language values for code execution.

Functions

This section is empty.

Types

type AuthInfo added in v0.21.0

type AuthInfo struct {
	Type           string   // "admin", "agent", "user", etc.
	AgentName      string   // Name of the agent token
	AllowedServers []string // Servers this token can access (nil = all)
	Permissions    []string // Permission tiers: "read", "write", "destructive"
}

AuthInfo carries authentication context for permission enforcement in JS execution. This is a simplified view of the auth.AuthContext to avoid circular imports.

func (*AuthInfo) CanAccessServer added in v0.21.0

func (a *AuthInfo) CanAccessServer(name string) bool

CanAccessServer checks whether this auth context can access the named server.

func (*AuthInfo) HasPermission added in v0.21.0

func (a *AuthInfo) HasPermission(perm string) bool

HasPermission checks whether this auth context includes the given permission.

type ErrorCode

type ErrorCode string

ErrorCode represents specific JavaScript execution error types

const (
	// ErrorCodeSyntaxError indicates invalid JavaScript syntax
	ErrorCodeSyntaxError ErrorCode = "SYNTAX_ERROR"

	// ErrorCodeRuntimeError indicates JavaScript runtime exception
	ErrorCodeRuntimeError ErrorCode = "RUNTIME_ERROR"

	// ErrorCodeTimeout indicates execution exceeded timeout limit
	ErrorCodeTimeout ErrorCode = "TIMEOUT"

	// ErrorCodeMaxToolCallsExceeded indicates max_tool_calls limit reached
	ErrorCodeMaxToolCallsExceeded ErrorCode = "MAX_TOOL_CALLS_EXCEEDED"

	// ErrorCodeServerNotAllowed indicates call_tool attempted to call disallowed server
	ErrorCodeServerNotAllowed ErrorCode = "SERVER_NOT_ALLOWED"

	// ErrorCodeSerializationError indicates result cannot be JSON-serialized
	ErrorCodeSerializationError ErrorCode = "SERIALIZATION_ERROR"

	// ErrorCodeTranspileError indicates TypeScript transpilation failed
	ErrorCodeTranspileError ErrorCode = "TRANSPILE_ERROR"

	// ErrorCodeInvalidLanguage indicates an unsupported language was specified
	ErrorCodeInvalidLanguage ErrorCode = "INVALID_LANGUAGE"
)

type ExecutionContext

type ExecutionContext struct {
	ExecutionID  string
	StartTime    time.Time
	EndTime      *time.Time
	Status       string // "running", "success", "error", "timeout"
	ToolCalls    []ToolCallRecord
	ResultValue  interface{}
	ErrorDetails *JsError
	// contains filtered or unexported fields
}

ExecutionContext tracks the state of a single JavaScript execution

func (*ExecutionContext) GetMaxPermissionLevel added in v0.21.0

func (ec *ExecutionContext) GetMaxPermissionLevel() string

GetMaxPermissionLevel returns the highest permission level used during execution.

type ExecutionOptions

type ExecutionOptions struct {
	Input          map[string]interface{} // Input data accessible as global `input` variable
	TimeoutMs      int                    // Execution timeout in milliseconds
	MaxToolCalls   int                    // Maximum number of call_tool() invocations (0 = unlimited)
	AllowedServers []string               // Whitelist of allowed server names (empty = all allowed)
	ExecutionID    string                 // Unique execution ID for logging (auto-generated if empty)
	Language       string                 // Source language: "javascript" (default) or "typescript"

	// Auth enforcement (Spec 031)
	AuthContext        *AuthInfo            // Auth context for permission enforcement (nil = no restrictions)
	ToolAnnotationFunc ToolAnnotationLookup // Function to look up tool annotations for permission checking
}

ExecutionOptions contains optional parameters for JavaScript execution

type JsError

type JsError struct {
	Message string    `json:"message"`
	Stack   string    `json:"stack,omitempty"`
	Code    ErrorCode `json:"code"`
}

JsError represents a JavaScript execution error with message, stack trace, and error code

func NewJsError

func NewJsError(code ErrorCode, message string) *JsError

NewJsError creates a new JsError with the given code and message

func NewJsErrorWithStack

func NewJsErrorWithStack(code ErrorCode, message, stack string) *JsError

NewJsErrorWithStack creates a new JsError with code, message, and stack trace

func TranspileTypeScript added in v0.21.0

func TranspileTypeScript(code string) (string, *JsError)

TranspileTypeScript transpiles TypeScript code to JavaScript using esbuild. It performs type-stripping only (no type checking or semantic validation). Returns the transpiled JavaScript code on success, or a JsError on failure.

func ValidateLanguage added in v0.21.0

func ValidateLanguage(language string) *JsError

ValidateLanguage checks if the given language string is supported. Returns nil if valid, or a JsError if not.

func (*JsError) Error

func (e *JsError) Error() string

Error implements the error interface

type Pool

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

Pool manages a pool of reusable JavaScript runtime instances for concurrent execution

func NewPool

func NewPool(size int) (*Pool, error)

NewPool creates a new JavaScript runtime pool with the specified size

func (*Pool) Acquire

func (p *Pool) Acquire(ctx context.Context) (*goja.Runtime, error)

Acquire obtains a runtime instance from the pool Blocks until an instance is available or context is cancelled

func (*Pool) Available

func (p *Pool) Available() int

Available returns the number of available instances in the pool

func (*Pool) Close

func (p *Pool) Close() error

Close closes the pool and releases all resources

func (*Pool) Release

func (p *Pool) Release(vm *goja.Runtime) error

Release returns a runtime instance to the pool

func (*Pool) Resize

func (p *Pool) Resize(newSize int) error

Resize adjusts the pool size (for hot configuration reload) If newSize > current size, adds new instances If newSize < current size, instances will be removed as they're released

func (*Pool) Size

func (p *Pool) Size() int

Size returns the configured pool size

type Result

type Result struct {
	// Ok indicates success (true) or error (false)
	Ok bool `json:"ok"`

	// Value contains the JavaScript return value if Ok=true (must be JSON-serializable)
	Value interface{} `json:"value,omitempty"`

	// Error contains error details if Ok=false
	Error *JsError `json:"error,omitempty"`
}

Result represents the outcome of JavaScript execution

func Execute

func Execute(ctx context.Context, caller ToolCaller, code string, opts ExecutionOptions) *Result

Execute runs JavaScript or TypeScript code in a sandboxed environment with tool call capabilities. When opts.Language is "typescript", the code is transpiled to JavaScript before execution.

func NewErrorResult

func NewErrorResult(err *JsError) *Result

NewErrorResult creates a Result with ok=false and the given error

func NewSuccessResult

func NewSuccessResult(value interface{}) *Result

NewSuccessResult creates a Result with ok=true and the given value

type ToolAnnotationLookup added in v0.21.0

type ToolAnnotationLookup func(serverName, toolName string) string

ToolAnnotationLookup is a function that returns the permission tier required for a tool. Returns one of "read", "write", "destructive".

type ToolCallRecord

type ToolCallRecord struct {
	ServerName  string                 `json:"server_name"`
	ToolName    string                 `json:"tool_name"`
	Arguments   map[string]interface{} `json:"arguments"`
	StartTime   time.Time              `json:"start_time"`
	DurationMs  int64                  `json:"duration_ms"`
	Success     bool                   `json:"success"`
	Result      interface{}            `json:"result,omitempty"`
	ErrorDetail interface{}            `json:"error_details,omitempty"`
}

ToolCallRecord represents a single call_tool() invocation

type ToolCaller

type ToolCaller interface {
	CallTool(ctx context.Context, serverName, toolName string, args map[string]interface{}) (interface{}, error)
}

ToolCaller is an interface for calling upstream MCP tools

Jump to

Keyboard shortcuts

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