jsruntime

package
v0.70.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const PermissionTierUnresolved = "unresolved"

PermissionTierUnresolved is the ToolAnnotationLookup outcome for a name the populated discovery snapshot of a KNOWN, CONNECTED server does not contain (Spec 105 FR-009, research D4). It is not a tier: no permission set — not even an administrator's, which passes every tier check — may dispatch a tool the proxy cannot identify, so checkDispatchGates refuses the call with PERMISSION_DENIED and the upstream is never asked. A lookup that has no opinion (server unknown, no runtime, or a snapshot emptied by the server's own state — quarantined, disabled, disconnected) keeps answering with a tier so the server-level verdicts downstream answer as they always did.

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 AuthzGateReport added in v0.68.0

type AuthzGateReport struct {
	Ctx             context.Context
	ParentID        string
	ServerName      string
	ToolName        string
	CanonicalTarget string // "server:tool"
	Denied          bool
	Code            ErrorCode // the envelope code of the refusal (SERVER_NOT_ALLOWED, ACCESS_DENIED, PERMISSION_DENIED)
	Message         string    // the envelope message shown to the script caller
	RequiredPerm    string    // the tier the lookup resolved, when one was resolved
	Arguments       map[string]interface{}
	BlockReason     string // host-defined typed cause of a profile policy refusal (Spec 108 FR-029); empty for every other refusal
}

AuthzGateReport is one pre-dispatch refusal decided inside the sandbox (Spec 107 T102/T104). Arguments is the caller's args map with every `_auth_`-prefixed key removed (FR-015) — the observer hashes it, never records it.

type AuthzObserver added in v0.68.0

type AuthzObserver interface {
	ObserveAuthzGate(report AuthzGateReport)
}

AuthzObserver receives AuthzGateReports. Implementations must be safe for concurrent use: call_tools() batch elements are gated on the script goroutine, but the observer contract does not promise that forever.

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"

	// ErrorCodeInvalidArgs indicates a host function was called with arguments
	// it cannot interpret (wrong arity, wrong types, malformed batch element)
	ErrorCodeInvalidArgs ErrorCode = "INVALID_ARGS"

	// ErrorCodeAccessDenied indicates the agent token cannot reach the server
	ErrorCodeAccessDenied ErrorCode = "ACCESS_DENIED"

	// ErrorCodePermissionDenied indicates the agent token lacks the permission
	// tier the requested tool needs
	ErrorCodePermissionDenied ErrorCode = "PERMISSION_DENIED"

	// ErrorCodeUpstreamError indicates the upstream tool call itself failed
	ErrorCodeUpstreamError ErrorCode = "UPSTREAM_ERROR"
)

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, unless RestrictToAllowed)
	ExecutionID    string                 // Unique execution ID for logging (auto-generated if empty)
	Language       string                 // Source language: "javascript" (default) or "typescript"
	MaxParallel    int                    // Default concurrency for call_tools() batches (0 = built-in default; per-batch options override this)

	// RestrictToAllowed enforces AllowedServers even when it is empty. Set by the
	// Spec 057 profile path: an active profile with an empty effective server set
	// (deny-all profile, or a non-overlapping token∩profile) must deny ALL
	// call_tool() invocations rather than fall back to the "empty = allow all"
	// default. Leave false for unrestricted code_execution and agent-token scopes.
	RestrictToAllowed bool

	// 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

	// ToolGateFunc is the gate-capturing form of ToolAnnotationFunc (Spec
	// 105 FR-009; codex r9 I1): it answers the same tier AND hands back the
	// opaque per-call gate the host resolved it from, which the dispatch
	// that follows consumes through GatedToolCaller instead of taking a
	// second, independent read. When set it takes precedence over
	// ToolAnnotationFunc; leave nil to keep the tier-only contract.
	ToolGateFunc ToolGateLookup

	// AuthzObserver, when set, receives one AuthzGateReport per scope or
	// permission REFUSAL resolveDispatchGates decides — the lone call_tool()
	// and every call_tools() batch element alike — so the host can write the
	// Spec 107 `authz deny` audit line for a nested call that never reaches
	// the ToolCaller (the completion emitters never see it). A refused call
	// is reported exactly once; an allowed call is not reported here at all
	// (its `authz allow` is the host's, written at dispatch). nil = no-op.
	AuthzObserver AuthzObserver
	// ParentID is the wrapper's correlation id, echoed on every report so the
	// nested line carries parent_id (contracts/audit-line-events.md).
	ParentID string
}

ExecutionOptions contains optional parameters for JavaScript execution

type GatedToolCaller added in v0.67.0

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

GatedToolCaller is the optional extension of ToolCaller a host implements to dispatch on the gate its ToolGateLookup captured for the same call. The sandbox uses it only when both are wired and the lookup returned a non-nil gate; every other combination dispatches through CallTool, unchanged.

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" — or PermissionTierUnresolved when the tool's identity cannot be resolved on a server the proxy knows, in which case the call is refused rather than authorized against any tier.

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

type ToolGate added in v0.67.0

type ToolGate interface{}

ToolGate is the opaque per-call capture a ToolGateLookup hands back beside the tier: whatever the host read to authorize the call, so the dispatch that follows runs on THAT read rather than on a second one that may disagree with it (Spec 105 FR-009; codex r9 I1). jsruntime never inspects it — it only carries it, unchanged, from the lookup to the dispatch of the same call. A nil gate means the lookup captured nothing and the dispatch falls back to ToolCaller.CallTool.

type ToolGateLookup added in v0.67.0

type ToolGateLookup func(serverName, toolName string) (tier string, gate ToolGate)

ToolGateLookup is ToolAnnotationLookup with the gate it decided the tier from: the tier follows the ToolAnnotationLookup contract exactly (including PermissionTierUnresolved), and the gate is handed to GatedToolCaller.CallToolWithGate if the call is authorized.

Jump to

Keyboard shortcuts

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