codemode

package
v1.18.1 Latest Latest
Warning

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

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

Documentation

Overview

Package codemode runs wick_run_code scripts. The script itself runs in a runner service plugin (codemode_<engine>, e.g. codemode_goja for JS/TS), never in wick: a runaway script can only take its runner down. Every connector call the script makes comes back to wick as a "call" event and is executed here, inside the caller's request, with the caller's session, user, tags and agent scope — the runner never sees a credential.

Wire (all under /_wick/codemode/, unreachable from outside wick):

POST /run     {run_id, lang, code, input, timeout_ms, call_timeout_ms, features}
              → 429 + status while the runner is over its memory share
              → 200 NDJSON: {"type":"call",id,tool_id,params,timeout_ms}… {"type":"file",id,op,path,data}…
                {"type":"done",ok,result,error,logs,features,timed_out}
POST /result  {run_id, id, ok, result|error}   (one per call or file event)
GET  /status  {heap_mb, budget_mb, running, busy, langs, engine}

Index

Constants

View Source
const (
	// DefaultTimeout, MaxTimeout and CallTimeout are the built-in limits;
	// the agents settings override them (Limits, CurrentLimits).
	DefaultTimeout = 120 * time.Second
	MaxTimeout     = 300 * time.Second
	// CallTimeout is one connector call's default deadline (shorter when the
	// run has less left). A call past it fails like any other failed call,
	// so the script can catch it and go on.
	CallTimeout = 60 * time.Second

	// MaxQueue is how long a run may wait for a busy runner before it gives up.
	MaxQueue = 2 * time.Minute
	// MaxResultBytes caps the result handed back to the model; the point of
	// Code Mode is to return a summary.
	MaxResultBytes = 20 << 10
	// MaxCalls bounds the connector calls of one run (a loop gone wrong).
	MaxCalls = 1000
)
View Source
const (
	// FilesDir is the one folder of the project a script may touch.
	FilesDir = "codemode"
	// MaxFileBytes caps one read or write.
	MaxFileBytes = 1 << 20
	// MaxFolderBytes and MaxFiles cap the whole codemode/ folder; a write
	// that would pass either is refused.
	MaxFolderBytes = 20 << 20
	MaxFiles       = 1000
)

wick.file: a script reads and writes files ONLY inside the codemode/ folder of its project folder, so an agent and its scripts can hand each other JSON/text. The runner never touches the disk: every op comes back as a "file" event and is done here, with these checks on every op.

View Source
const (
	KeyDefaultTimeout = "codemode_default_timeout_sec"
	KeyMaxTimeout     = "codemode_max_timeout_sec"
	KeyCallTimeout    = "codemode_call_timeout_sec"
)

Settings keys (owner "agents") an admin sets the limits with, in seconds.

View Source
const DefaultRunnerKey = "codemode_goja"

DefaultRunnerKey is the runner wick downloads on its own when a run finds none installed.

View Source
const EnvAutoInstall = "WICK_CODEMODE_AUTO_INSTALL"

EnvAutoInstall turns that download off when set to 0, false or off.

View Source
const FeatureFile = "file"

FeatureFile is announced by both sides (run request, done event) when they speak the "file" event.

View Source
const HardMaxTimeout = time.Hour

HardMaxTimeout bounds every setting: a typo of 30000 must not keep a run (and its runner slot) for days.

View Source
const RunnerPrefix = "codemode_"

RunnerPrefix marks a service plugin as a Code Mode runner.

Variables

View Source
var ErrAutoInstallOff = errors.New("automatic runner download is off (" + EnvAutoInstall + ")")

ErrAutoInstallOff means the runner download is turned off by EnvAutoInstall.

View Source
var ErrFileDenied = errors.New("wick.file path denied")

ErrFileDenied marks a path refused for where it leads (absolute, .., a symlink out of codemode/); errors.Is reports it.

View Source
var ErrNoRunner = errors.New("no Code Mode runner is installed for this language")

ErrNoRunner means no installed runner takes the language.

Functions

func AutoInstallEnabled

func AutoInstallEnabled() bool

AutoInstallEnabled reports whether EnvAutoInstall allows the download.

func FileOp

func FileOp(dir, op, rel, data string) (json.RawMessage, error)

FileOp runs one wick.file op for the project folder dir and returns its JSON result: read → string, write → {path, bytes}, list → FileEntry, exists → bool.

func ManualInstallHint

func ManualInstallHint() string

ManualInstallHint tells an admin how to install the runner by hand.

func SetLimitsSource

func SetLimitsSource(fn func() Limits)

SetLimitsSource makes fn the source of CurrentLimits. It is read on every run, so a settings change applies to the next run without a restart. nil = the built-in constants.

func ToolIDs

func ToolIDs(code string) []string

ToolIDs returns the distinct tool_id literals written in code, sorted.

Types

type Call

type Call struct {
	ToolID      string `json:"tool_id"`
	Label       string `json:"label,omitempty"`
	OK          bool   `json:"ok"`
	Destructive bool   `json:"destructive,omitempty"`
	MS          int64  `json:"ms"`
	Error       string `json:"error,omitempty"`
}

Call is one connector call recorded during a run.

type FileEntry

type FileEntry struct {
	Path     string `json:"path"`
	Size     int64  `json:"size"`
	Modified string `json:"modified"`
}

FileEntry is one item of wick.file.list.

type Host

type Host struct {
	Runners Runners
	// Check vets one tool_id before the run starts (exists, visible to the
	// caller). A nil Check skips the pre-flight.
	Check func(ctx context.Context, toolID string) error
	// Exec runs one connector call as the caller.
	Exec func(ctx context.Context, toolID string, params map[string]any) (string, error)
	// Describe labels a tool_id for the call list (connector label, whether
	// the op is destructive). Optional.
	Describe func(toolID string) (label string, destructive bool)
	// Install, when set, runs when no runner is installed at all (see
	// Installer.Ensure); the run then picks again from Runners. Optional.
	Install func(ctx context.Context) error
}

Host is what a run needs from wick.

func (Host) Run

func (h Host) Run(ctx context.Context, req Request) (*Result, error)

Run executes req. Failures of the script itself come back as a Result with OK=false; an error is returned only when the run could not happen at all.

type Installer

type Installer struct {
	// Install downloads, verifies and loads the runner live. It returns once
	// the runner is registered with the service host.
	Install func(ctx context.Context) error
	// Enabled gates the download; nil means AutoInstallEnabled.
	Enabled func() bool
	// contains filtered or unexported fields
}

Installer installs the default runner once for every run that needs it: the first caller starts the install, concurrent callers wait for the same result. The install itself is detached from the callers' contexts, so one caller giving up does not abort it for the rest.

func (*Installer) Ensure

func (i *Installer) Ensure(ctx context.Context) error

Ensure installs the runner, or waits for the install already running.

type Limits

type Limits struct {
	// Default is a run's deadline when the caller asks for none.
	Default time.Duration
	// Max caps the deadline a caller asks for.
	Max time.Duration
	// Call is one connector call's default deadline.
	Call time.Duration
}

Limits are the run and call deadlines Code Mode applies. A zero field means the built-in constant.

func CurrentLimits

func CurrentLimits() Limits

CurrentLimits are the limits in force now, normalized.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are the built-in constants.

func ParseLimits

func ParseLimits(get func(key string) string) Limits

ParseLimits reads the three settings through get (key → raw value). Empty, non-numeric and <=0 values fall back to the constants.

func (Limits) Clamp

func (l Limits) Clamp(d time.Duration) time.Duration

Clamp is the deadline of a run that asked for d (0 = none).

func (Limits) Normalize

func (l Limits) Normalize() Limits

Normalize fills unset or nonsense fields with the constants and keeps the three consistent: Default never above Max, Call never above Max.

type Request

type Request struct {
	Lang    string
	Code    string
	Input   json.RawMessage
	Timeout time.Duration
	// Dir is the project folder whose codemode/ subfolder wick.file uses
	// (FileOp). Empty = no wick.file; NoDir then says why.
	Dir   string
	NoDir string
}

Request is one script run.

type Result

type Result struct {
	OK         bool            `json:"ok"`
	Result     json.RawMessage `json:"result,omitempty"`
	Error      string          `json:"error,omitempty"`
	Logs       []string        `json:"logs,omitempty"`
	Calls      []Call          `json:"calls"`
	Truncated  bool            `json:"truncated,omitempty"`
	DurationMS int64           `json:"duration_ms"`
	QueuedMS   int64           `json:"queued_ms,omitempty"`
	Runner     string          `json:"runner,omitempty"`
	RunID      string          `json:"run_id"`
}

Result is what wick_run_code returns.

type Runner

type Runner struct {
	Key   string
	Langs []string
	// Transport reaches the plugin's socket (waking it when it sleeps).
	Transport func() (http.RoundTripper, error)
}

Runner is one Code Mode runner plugin.

type Runners

type Runners func() []Runner

Runners lists the installed runners.

func PluginRunners

func PluginRunners(host func() *plugin.Host) Runners

PluginRunners lists the codemode_* service plugins of host. A runner's languages come from its /status, fetched once per installed version (the first run wakes it anyway).

Directories

Path Synopsis
Package scriptpath reads a Code Mode script from a file relative to a project folder (script_path), with the same confinement for every caller: the watch code step, wick_run_code and the run_code workflow node.
Package scriptpath reads a Code Mode script from a file relative to a project folder (script_path), with the same confinement for every caller: the watch code step, wick_run_code and the run_code workflow node.

Jump to

Keyboard shortcuts

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