Documentation
¶
Overview ¶
Package starcore is the server-safe Starlark runtime of a plugin script. It is the runtime without the half that only a client needs: the program loader and runner, the registrar mechanism (a host adds the kinds of registration), Script.Invoke with its limits, and the settings, log, env and http builtins. It imports internal/plugin/core and the interpreter and nothing that writes into other people's home directories (internal/provisioning, internal/plugin) or reads the server's configuration, so a server-side caller such as the Surveyor can link it (internal/boundaries holds it). Package star builds the command, tool and event kinds and the files and kb modules on top of it.
Together with package star it is the only code that imports go.starlark.net (TestStarlarkIsConfined holds it).
A script runs in two phases. LOAD runs plugin.star once, with only the registration builtins (command, tool, on), the pure modules (json, math, and time without now) and capability modules that refuse every call, and reports what the script registered; what a user approves is a pure function of the tree, so LOAD reads no clock, no setting and no file. CALL runs a registered function on demand, on a fresh thread, under step and time caps, with typed errors (CallError) and the settings of the call.
Starlark binds the names of a function when the function is created, so the modules are values whose behavior is decided at the call, from the context kept in the running thread (callCtx): a function defined while loading must see the CALL-time context when it runs. A thread-less attribute read (settings.x) cannot do that: see settingsValue.
Index ¶
- Constants
- Variables
- func CapText(s string) (string, error)
- func CheckText(fn, what, s string) error
- func CtxStruct(fields map[string]any) (starlark.Value, error)
- func DeniedErr(format string, a ...any) error
- func EncodeJSON(ctx context.Context, w *bytes.Buffer, v starlark.Value, depth int) error
- func EscapeLines(s string) string
- func ImplFunc(fn string, v starlark.Value) (*starlark.Function, error)
- func InCallPhase(_ seam.Gate, t *starlark.Thread)
- func LimitErr(format string, a ...any) error
- func Merge(ds ...starlark.StringDict) starlark.StringDict
- func ParamsSchema(thread *starlark.Thread, v starlark.Value) ([]byte, error)
- func ToStarlark(v any) (starlark.Value, error)
- type CallCtx
- type CallError
- type CallSpec
- type ErrKind
- type Exchange
- type File
- type LoadError
- type Options
- type Registration
- type Registry
- type Replay
- type Script
Constants ¶
const ( // MaxLoadSteps caps the interpreter steps of loading plugin.star and each // lib file, so a top-level script that never ends fails the load. MaxLoadSteps uint64 = 20_000_000 // MaxRegistrationText caps a help, usage or description string. MaxRegistrationText = 1024 // Per-call step caps: a command is the user's own run, a tool or an event // is a bridge request or a hook. MaxCallStepsTool uint64 = 20_000_000 MaxCallStepsCommand uint64 = 500_000_000 // MaxCallStepsRecipe caps one verb call of a Surveyor recipe: it pages // through a source, so it gets more than a tool. MaxCallStepsRecipe uint64 = 100_000_000 // MaxPrintBytes caps what print and log write in one call; the rest is // dropped and a "truncated" line ends the output. MaxPrintBytes = 64 << 10 // MaxResultBytes caps the text a tool or command returns. MaxResultBytes = 1 << 20 )
Limits of one run, named in one place. Starlark has no allocation cap, and the tree reader loads a script before any approval, so memory is bounded by a watchdog (watchHeap, D1746, #1741): while a thread runs it samples the live heap and cancels the thread when the heap has grown past MaxHeapGrowth over its value at the start (one baseline for a whole call, its re-run of plugin.star included). It is approximate by design, in both directions: the metric counts garbage not yet swept and the allocations of every other goroutine, so it can fire on a script that did little in a process with a large or busy heap, and one huge allocation between two samples can pass the cap. It bounds the common case, a script that keeps allocating, not a single hostile allocation. A plugin is trusted only as far as it was approved; ReadTree runs the scripts only on an otherwise valid tree, and sync compares the digest first.
const ( ToolTimeout = 30 * time.Second EventTimeout = 10 * time.Second // RecipeTimeout is one verb call of a Surveyor recipe. RecipeTimeout = 5 * time.Minute )
Wall clock of one call; a command has none (it ends when done or on Ctrl-C). A caller's context can only shorten them.
const ( MaxHTTPResponseBytes = 8 << 20 MaxHTTPRequestBytes = 4 << 20 MaxHTTPRequests = 50 MaxHTTPRedirects = 10 // HTTPTimeout is the default for one request; the call's own deadline can // only shorten it. HTTPTimeout = 30 * time.Second )
Network caps of one call (http.request).
const ( // MaxFileBytes caps one files.read and one files.write. MaxFileBytes = 8 << 20 // MaxGlobResults caps what files.glob returns; the walk stops there. MaxGlobResults = 1000 // MaxGlobVisits caps the directory entries one files.glob looks at. MaxGlobVisits = 100_000 MaxGlobDepth = 32 )
File caps of one call (files.*).
Variables ¶
var ( MaxHeapGrowth uint64 = 256 << 20 HeapSampleEvery = 5 * time.Millisecond )
MaxHeapGrowth is how far the live heap may grow during one run (a load, or the thread of a call) before it is cancelled. HeapSampleEvery is how often the watchdog looks. Variables, not constants, so a test can use a small cap.
Functions ¶
func DeniedErr ¶
denied builds the error of a capability the manifest does not grant. The text may hold script- or network-supplied data, so it is escaped here, once.
func EncodeJSON ¶
EncodeJSON writes v as compact JSON and stops with LimitExceeded as soon as the output passes MaxResultBytes, so shared substructure (x = [x, x] again and again) costs a bounded amount of work; it also honours the call's context.
func EscapeLines ¶
EscapeLines escapes each line of a multi-line text.
func InCallPhase ¶
InCallPhase puts a bare thread in the CALL phase: the seam of tests that call a registered function outside Invoke, gated by the token only startest holds.
func Merge ¶
func Merge(ds ...starlark.StringDict) starlark.StringDict
func ParamsSchema ¶
ParamsSchema turns the params dict of a tool into the JSON of an object schema and checks it resolves, once, at load.
Types ¶
type CallCtx ¶
type CallCtx struct {
// The rest is set for a CALL only.
Plugin string
Log io.Writer // the call's log sink: log.* and, for a tool or event, print
Ctx context.Context
// perms are the manifest's granted permissions; the capability modules of
// the following changes read them here, never from the script.
Perms *core.Permissions
LookupEnv func(string) (string, bool)
// ext is the state the host's own modules keep for the call (Ext of the
// CallSpec): the runtime never reads it.
Ext any
// contains filtered or unexported fields
}
CallCtx is what a run knows besides its Starlark values; one per thread, and threads are never shared. The modules read it when they are called, not when they are created, because a Starlark function keeps the predeclared names of the load that made it (the trap the package comment names).
type CallError ¶
type CallError struct {
Kind ErrKind
// Msg is the message for the user: for fail() the script's own text, for
// any other error the message with its position.
Msg string
// Trace is the Starlark backtrace, when the error has one.
Trace string
}
CallError is what Call returns when the call did not succeed.
type CallSpec ¶
type CallSpec struct {
Kind, Name string // the registration called
Plugin string // for the log prefix and the User-Agent
Version string // sent in http.request's User-Agent
Perms *core.Permissions
Declared map[string]core.Setting
Values map[string]any
// LookupEnv reads the environment for env.get; nil is os.LookupEnv.
LookupEnv func(string) (string, bool)
// PrivateHosts are the hosts the host grants a private address: the
// Surveyor config's allow_private_hosts. http.request honours one only when
// Perms.NetPrivate declares it too; the client never sets it.
PrivateHosts []string
// Replay, when set, answers http.request from recordings and never touches a
// network (replay.go). Only `plugin test` sets it; the Surveyor never does.
Replay *Replay
// Log receives log.* and print; with PrintToStdout print goes to Stdout
// instead, without prefix. Nil discards.
Log, Stdout io.Writer
PrintToStdout bool
// Timeout is the wall clock (0 none); Steps the step cap of the whole call,
// which the host always sets (the default per kind is the host's).
Timeout time.Duration
Steps uint64
// Arg builds the arguments the impl is called with; its errors are *CallError.
Arg func(reg *Registration) (starlark.Tuple, error)
// Result reads the value the impl returned; ctx carries the call's deadline.
Result func(ctx context.Context, v starlark.Value) (any, error)
// Ext builds the state of the modules the host adds (CallCtx.ext); nil for none.
Ext func(cc *CallCtx) any
// Same compares what two runs of the script registered; nil is sameRegistrations.
Same func(a, b []Registration) bool
// Seams are the test seams of a call; only startest can build one.
Seams *seam.Seams
}
CallSpec is one call, as the runtime sees it. The command, tool and event kinds live in the client half (request.go): it decides what the impl is given (Arg), how its result is read (Result), which state the client-only modules keep in the call's context (Ext), the wall clock and the step cap.
type ErrKind ¶
type ErrKind int
ErrKind is how a call failed, for the caller to map to an exit code or an MCP error.
const ( // Failed is the script's own failure: fail(), a runtime error, a bad // argument, a bad setting. Failed ErrKind = iota + 1 // Denied is a capability the manifest does not grant. Denied // LimitExceeded is a cap hit: steps, time, size or count. LimitExceeded // Cancelled is the caller's context cancelled (Ctrl-C). Cancelled // Internal is a bug of the host: a panic, an impl that is not there. Internal )
type Exchange ¶
type Exchange struct {
Method string
// URL is scheme://host/path, with or without its own query.
URL string
// Query is added to the URL's own query; the request's must equal the sum.
Query map[string]string
Status int // 0 is 200
Headers map[string]string
Body string
}
Exchange is one recorded answer of Replay.
type File ¶
type File struct {
Path string `json:"path"`
Lines int `json:"lines"`
Bytes int `json:"bytes"`
SHA256 string `json:"sha256"`
}
File is a script file of the tree.
type LoadError ¶
type LoadError struct {
Msg string // "file:line:col: reason", or the reason alone
// Trace is the Starlark backtrace, when the failure has one.
Trace string
}
LoadError is a script that does not load, with the position of the failure.
type Options ¶
type Options struct {
Registrars starlark.StringDict
Extra starlark.StringDict
// Entry is the script that registers; "" is plugin.star, the client's. The
// surveyor side's is surveyor.star, a single file that loads nothing.
Entry string
}
Options say what the host adds to the language: the registrars only plugin.star has (the kinds of a registration) and the capability modules beyond the runtime's own (settings, log, http, env).
type Registration ¶
type Registration struct {
Kind string // the registrar that made it: its host names them
Name string // command or tool name, or the event
// Help is a command's help, a tool's description; Usage a command's usage.
Help, Usage string
// Params is a tool's JSON schema (an object schema), as JSON.
Params []byte
Writes bool
// Pos is where the Registering call stands, "file:line".
Pos string
// Impl is the function the script registered.
Impl *starlark.Function
}
Registration is one contribution the script made while loading.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry collects what plugin.star registers while it loads.
func Registering ¶
Registering is the first step of a registrar: the registry of the run that is loading plugin.star (an error anywhere else) and the position of the registering call, "file:line".
type Replay ¶
type Replay struct{ Exchanges []Exchange }
Replay makes http.request answer from recordings, for `plugin test`.
It is not a seam: the host still runs the checks http.request makes before it goes to the network (method, scheme, credentials in the url, the permissions.net allow-list, the header rules, the caps and, for a recorded 3xx, the redirect rules), then answers from the recording. It can only ever hand back canned data and cannot reach a network, so a script cannot use it to learn anything; a request with no recording fails naming method and url.
GAP: nothing is resolved or dialed, so the checks that judge the address a name resolves to do not run: the refusal of a private, loopback or link-local address and the two-key net_private grant (the manifest's permission and the operator's host list) are not exercised. A recipe that reaches a private host passes a replay and still needs the grant in a real Surveyor. TRAP: nothing the Surveyor runs may set CallSpec.Replay (internal/boundaries pins it): a Surveyor that replayed would poll recorded data as if it were live.
type Script ¶
type Script struct {
Files []File
Registrations []Registration
// contains filtered or unexported fields
}
Script is a loaded plugin script: its files and what it registered, in the order the script registered them. Its functions are frozen.
func LoadScript ¶
LoadScript runs plugin.star once, with lib/*.star loadable from it, and reports what it registered. It reads the files it is given and nothing else. A tree without plugin.star and without lib/ is not a script plugin: (nil, nil).
func LoadSources ¶
LoadSources runs plugin.star over srcs as LoadScript does, without the checks of a tree (sizes, names, caps): the seam of tests that need a script shaped by hand, gated by the token only startest holds.
func (*Script) Invoke ¶
Invoke runs one registered function on a fresh thread and returns what spec.Result made of its value. The error, when there is one, is a *CallError.
func (*Script) ReplaceSource ¶
ReplaceSource swaps a source the next call runs again: a test seam, gated by the token only startest holds.
func (*Script) Sorted ¶
func (p *Script) Sorted() []Registration
Sorted returns the registrations by kind, then name: a stable listing.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
seam
Package seam holds the test seams of the Starlark runtime.
|
Package seam holds the test seams of the Starlark runtime. |
|
Package recipes is the surveyor side of the Starlark runtime: the recipe() registrar of surveyor.star and the call of a recipe's verbs (spec, check, list, fetch).
|
Package recipes is the surveyor side of the Starlark runtime: the recipe() registrar of surveyor.star and the call of a recipe's verbs (spec, check, list, fetch). |
|
Package startest is the door of the tests to the test seams of starcore.
|
Package startest is the door of the tests to the test seams of starcore. |