# Wago documentation: complete corpus Canonical source: https://docs.wago.sh/ Page count: 81 This file is generated from the same Markdown sources as the human-facing documentation. --- Source page: https://docs.wago.sh/beta/getting-started Markdown: https://docs.wago.sh/raw/beta/getting-started.md # Getting started This guide takes you from an empty machine to a successful WebAssembly call. You will install the Wago version manager, select a runtime, download a tiny module, and run it. ![Installing Wago and selecting a canary runtime](/demos/install.gif) ## Install the manager ::: code-group ```bash [Go Install] go run github.com/wago-org/wago/cli/wago-installer@latest ``` ```bash [macOS / Linux] curl -fsSL https://install.wago.sh/unix | sh ``` ```powershell [PowerShell] irm https://install.wago.sh/ps | iex ``` ```sh wago --version ``` You can think of the wago command as a **version manager**. It handles version installing, upgrading, and switching. In order to run wasm, you need to install the actual runtime. If you only need Wago as a library in an existing Go project, add the package directly: ```sh go get github.com/wago-org/wago ``` ## Install a runtime ```sh wago version install ``` ## Download a small module ![Downloading, inspecting, and running the Fibonacci module](/demos/run-fib.gif) ```sh curl -fsSL https://wago.sh/corpora/fib.wasm -o fib.wasm ``` This module exports a function named `fib`. It takes one `i32` argument and returns the corresponding Fibonacci number. You can inspect its exports before running it: ```sh wago module exports fib.wasm ``` The module exports a `fib (i32) -> i32` function. Without `--invoke`, Wago selects `_start`, then `main`, then the module's only exported function—in this case, `fib`. If several exported functions remain, name one with `--invoke` or `-e`. ## Run it In this case, `fib` is the only exported function, so Wago selects it automatically: ```sh wago fib.wasm 30 ``` You should see: ```text 832040 ``` ## Try the everyday commands > Wago uses either [Go 1.22 or newer](https://go.dev/) or [TinyGo 0.41.1](https://tinygo.org/getting-started/install/), the tested TinyGo baseline, to link standalone executables. Make sure one of them is available on `PATH`. Create a standalone executable: ::: code-group ```bash [macOS / Linux] wago compile fib.wasm -o fib ./fib 30 ``` ```powershell [PowerShell] wago compile fib.wasm -o fib.exe .\fib.exe 30 ``` ```cmd [Command Prompt] wago compile fib.wasm -o fib.exe fib.exe 30 ``` ## Where to go next ### [Use the CLI well](./guides/cli) Pick exports, pass typed arguments, watch files, inspect imports, and precompile modules. ### [Embed Wago in Go](./guides/embed/runtime-and-modules) Move from a shell command to a long-lived runtime inside your application. ### [Add host capabilities](./using-plugins) Install the WASI plugin, review its requested access, and run a module that uses it. ### [Fix a first-run problem](./troubleshooting) Diagnose PATH, runtime selection, imports, exports, and stale precompiled files. --- Source page: https://docs.wago.sh/beta/guides/cli Markdown: https://docs.wago.sh/raw/beta/guides/cli.md # Use the CLI [Getting started](../getting-started) covers installation, running a module, and compiling an executable. This page contains the module operations that go beyond that path. ## Invoke an export Select a function and pass its arguments after the module path: ```sh wago run --invoke fib fib.wasm 30 ``` Use `30:i32`, `30:i64`, `30:f32`, or `30:f64` when the type must be explicit. Put Wago flags before the module path. ## Inspect and validate Inspect a module without executing it: ```sh wago module imports fib.wasm wago module exports fib.wasm wago module capabilities fib.wasm wago validate fib.wasm ``` Add `--json` when another program needs the output. ## Develop Rerun when the module changes or parallelize work on a large module: ```sh wago run --watch --invoke fib fib.wasm 20 wago run --parallel=4 --invoke fib fib.wasm 20 ``` Parallelism adds overhead to small modules. Measure before keeping it enabled. ## Debug a trap Reproduce the exact export and arguments outside watch mode. If validation passes, Wago reports the trap reason and any Wasm frames: ```sh wago run --invoke process module.wasm 42 ``` `context.Canceled` and `context.DeadlineExceeded` are host cancellation, not guest traps. ## Cache native code Build a host-specific `.wago` artifact when startup compilation matters: ```sh wago build fib.wasm -o fib.wago wago run --allow-native-artifact fib.wago 20 ``` A `.wago` file contains native code. Run only artifacts you trust, retain the original Wasm, and rebuild for each architecture or incompatible Wago release. --- Source page: https://docs.wago.sh/beta/guides/cli/configuration Markdown: https://docs.wago.sh/raw/beta/guides/cli/configuration.md # Configure and manage Wago Command flags affect one run. Save only defaults you expect to reuse. ## Save configuration Inspect overrides, then set or remove the smallest required value: ```sh wago config diff --local wago config set optimizations.inline off --local wago config reset optimizations.inline --local ``` Use `--global` for user-wide defaults. Project settings live in `wago.json`; create it with `wago init --run`. ## Install completions ```sh wago config completions zsh --install ``` Replace `zsh` with `bash` or `fish`. Use `--dry-run` to preview the change. ## Select a runtime Switch to beta, canary, or an exact tested commit: ```sh wago version switch beta wago version switch canary wago version install --version --use --no-input ``` Use `wago version current` to record the exact selection. Rolling channels move. ## Choose a build `standard` is the complete profile; `minimal` is run-only. `normal` uses standard Go; `tiny` uses TinyGo. ```sh wago version install --canary --profile minimal --build tiny --use ``` ## Update Preview coordinated updates before applying them: ```sh wago update --all --dry-run --json wago update --all ``` In CI, install an exact commit with `--no-input` instead of following a rolling channel. --- Source page: https://docs.wago.sh/beta/guides/embed/artifacts Markdown: https://docs.wago.sh/raw/beta/guides/embed/artifacts.md # Cache compiled code A `.wago` artifact stores host-native compiled code. It removes compilation from startup, but it is specific to Wago's artifact format, the target operating system, and the target architecture. Use the `fib.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("fib.wasm") if err != nil { return err } compiled, err := wago.Compile(nil, wasm) if err != nil { return err } artifact, err := compiled.MarshalBinary() closeErr := compiled.Close() if err != nil { return err } if closeErr != nil { return closeErr } if err := os.WriteFile("fib.wago", artifact, 0o600); err != nil { return err } trustedBytes, err := os.ReadFile("fib.wago") if err != nil { return err } trusted, err := wago.LoadTrustedArtifact(trustedBytes) if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.AdoptModule(trusted) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer instance.Close() results, err := instance.InvokeValues(ctx, "fib", wago.ValueI32(20)) if err != nil { return err } fmt.Printf("artifact: %d bytes\n", len(artifact)) fmt.Println(results[0].I32()) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` The artifact size varies by Wago version and architecture. The final line remains: ```text 6765 ``` ## Treat artifacts as executable code `LoadTrustedArtifact` is intentionally explicit: a `.wago` file contains native machine code. Load only bytes produced locally or authenticated by your application. Use normal `Runtime.Compile` for untrusted `.wasm` input. Keep the original Wasm. Rebuild artifacts after an incompatible Wago update and for every operating-system and architecture target you ship. If plugins or custom compiler extensions affect compilation, build and load the artifact through the same runtime configuration and plugin generation. --- Source page: https://docs.wago.sh/beta/guides/embed/calls-and-state Markdown: https://docs.wago.sh/raw/beta/guides/embed/calls-and-state.md # Work with calls and state `Instance.InvokeValues` checks typed arguments against the export signature and uses the supplied context for cancellation. | Wasm type | Go argument | Read a result | |---|---|---| | `i32` | `wago.ValueI32(v)` | `result.I32()` | | `i64` | `wago.ValueI64(v)` | `result.I64()` | | `f32` | `wago.ValueF32(v)` | `result.F32()` | | `f64` | `wago.ValueF64(v)` | `result.F64()` | Use `Invoke` for raw ABI slots without a caller-supplied context, or `InvokeContext` when raw-slot execution also needs cancellation. Resolve repeated calls once with `WasmFunc`; its `Invoke` method accepts every arity and performs lifecycle admission for each call. ## See instance state survive Create `counter.wat`: ```wat (module (global $count (export "count") (mut i32) (i32.const 0)) (func (export "inc") (result i32) global.get $count i32.const 1 i32.add global.set $count global.get $count)) ``` Compile it with [WABT](https://github.com/WebAssembly/wabt): ```sh wat2wasm counter.wat -o counter.wasm ``` Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("counter.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err }; defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err }; defer instance.Close() for range 3 { results, err := instance.InvokeValues(ctx, "inc") if err != nil { return err }; fmt.Println(results[0].I32()) } count, err := instance.GlobalValue("count") if err != nil { return err } fmt.Println("count:", count.I32()) if err := instance.SetGlobalValue("count", wago.ValueI32(40)); err != nil { return err } results, err := instance.InvokeValues(ctx, "inc") if err != nil { return err }; fmt.Println("after set:", results[0].I32()) fresh, err := runtime.Instantiate(ctx, module) if err != nil { return err }; defer fresh.Close() results, err = fresh.InvokeValues(ctx, "inc") if err != nil { return err }; fmt.Println("fresh instance:", results[0].I32()) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 1 2 3 count: 3 after set: 41 fresh instance: 1 ``` One instance preserves state and accepts one call at a time. A fresh instance starts with the module's initial state while reusing the same compiled code. ## Read and write memory safely Use checked copies for ordinary host access: ```go data, ok := instance.Read(offset, length) if !ok { return fmt.Errorf("guest memory range is out of bounds") } if ok := instance.Write(offset, replacement); !ok { return fmt.Errorf("guest memory range is out of bounds") } ``` `Read` returns a copy. `Write` either copies the whole slice or changes nothing. Typed little-endian helpers such as `ReadUint32Le` and `WriteUint32Le` are available for scalar fields. `instance.Memory().UnsafeBytes()` is a zero-copy mutable view. Use it only when you can keep the view inside a tightly controlled operation; never retain it after closing the instance. --- Source page: https://docs.wago.sh/beta/guides/embed/host-functions Markdown: https://docs.wago.sh/raw/beta/guides/embed/host-functions.md # Let Wasm call Go A host function supplies an import declared by the guest. Start with an ordinary typed Go function; use the lower-level `HostFunc` form only when the callback needs the calling instance or its memory. ## Bind a typed function The guest declares `host.mul(i32, i32) -> i32`, then uses it to implement `square`. Pick the language you want to embed. ### WAT Create `guest/square.wat`: ```wat (module (import "host" "mul" (func $mul (param i32 i32) (result i32))) (func (export "square") (param $value i32) (result i32) local.get $value local.get $value call $mul)) ``` ```sh wat2wasm guest/square.wat -o square.wasm ``` ### AssemblyScript Create `guest/square.ts`: ```ts @external("host", "mul") declare function mul(a: i32, b: i32): i32; export function square(value: i32): i32 { return mul(value, value); } ``` ```sh npx --yes --package assemblyscript@0.28.8 asc \ guest/square.ts --runtime stub --optimize --noAssert \ --outFile square.wasm ``` ### TinyGo Create `guest/main.go`: ```go //go:build tinygo package main //go:wasmimport host mul func mul(a, b int32) int32 //go:wasmexport square func square(value int32) int32 { return mul(value, value) } func main() {} ``` ```sh tinygo build -target=wasm-unknown -no-debug \ -o square.wasm ./guest ``` Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "slices" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("square.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() imports := wago.NewImports() imports.HostFunc("host", "mul", func(a, b int32) int32 { return a * b }) instance, err := runtime.Instantiate( ctx, module, wago.WithImports(imports), ) if err != nil { return err } defer instance.Close() if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeValues(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeValues(ctx, "square", wago.ValueI32(9)) if err != nil { return err } fmt.Println(results[0].I32()) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 81 ``` `HostFunc` keeps the Wasm module name and field name separate, so it remains unambiguous even when either contains a dot. Wago checks the Go function against the guest's declared signature during instantiation. Configure an import collection before first use; instantiation seals it, after which it can be reused concurrently but cannot be modified. WAT spells the import directly, AssemblyScript uses `@external`, and TinyGo uses `//go:wasmimport`. All three produce the same WebAssembly boundary, so the host binding does not change. ## Read caller memory Pointer-length pairs from a guest are untrusted. Use the caller-aware `HostCall` form when a callback needs guest memory: ```go imports := wago.NewImports() imports.HostFunc("env", "write", func(caller wago.Caller, call wago.HostCall) { ptr := uint32(call.I32(0)) length := uint32(call.I32(1)) memory := caller.Memory() end := uint64(ptr) + uint64(length) if end > uint64(len(memory)) { call.SetI32(0, -1) return } data := append([]byte(nil), memory[ptr:end]...) fmt.Printf("guest says %q\n", data) call.SetI32(0, int32(length)) }).Params(wago.ValI32, wago.ValI32).Results(wago.ValI32) ``` Pass the collection during instantiation: ```go wago.WithImports(imports) ``` Use a wider integer for `ptr + length` so the addition cannot wrap before the bounds check. `HostCall`, its raw slot views, the memory view, and `Caller` are valid only during the callback. Copy anything that must survive it, and do not send borrowed values to another goroutine. ## Re-enter Wasm deliberately A caller-aware callback may synchronously invoke an export through `InvokeFromHost` while its `Caller` is active: ```go out, err := instance.InvokeFromHost(ctx, caller, "normalize", wago.I32(value)) ``` Use this only for guest APIs that require synchronous re-entry. The caller token is scoped to the callback and fails closed after it returns. One invocation chain may have at most four active `InvokeFromHost` calls across all instances; a fifth returns `wago.ErrPermissionDenied`. Each call still performs lifecycle admission, and no `WasmFunc` keeps an instance reserved between calls. ## Define failures deliberately Wasm has no built-in Go `error` result. Prefer an explicit guest ABI such as a numeric status, a sentinel result, or an output buffer. When the callback cannot continue the current invocation, abort it with the original error: ```go panic(wago.HostTrap{Err: err}) ``` Wago recovers `HostTrap` at the native boundary and returns its error to the caller. An unexpected Go panic is a programming failure, not a guest error channel. Host functions run as trusted Go in your process. Give each closure the narrowest interface it needs. Runtime policy limits declared guest capabilities and resources; it does not sandbox the Go callback itself. --- Source page: https://docs.wago.sh/beta/guides/embed/limits-and-policy Markdown: https://docs.wago.sh/raw/beta/guides/embed/limits-and-policy.md # Add limits and cancellation There are three separate boundaries: - `RuntimeConfig` controls compilation and runtime-wide resource ceilings. - `Policy` checks one module when an instance is created. - `context.Context` controls how long instantiation and calls may continue. ## Run with explicit boundaries Use the `fib.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "time" "github.com/wago-org/wago" ) func run() error { wasm, err := os.ReadFile("fib.wasm") if err != nil { return err } config := wago.NewRuntimeConfig(). WithMaxModuleBytes(16<<20). WithMemoryLimitPages(256). WithMaxFunctionLocals(4096). WithInstanceLimits(8, 0) if err := config.Validate(); err != nil { return err } runtime := wago.NewRuntime(wago.WithRuntimeConfig(config)) defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() policy := wago.Policy{ MaxMemories: 1, MaxTableEntries: 1024, } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() instance, err := runtime.Instantiate(ctx, module, wago.WithPolicy(policy)) if err != nil { return err } defer instance.Close() results, err := instance.InvokeValues(ctx, "fib", wago.ValueI32(20)) if err != nil { return err } fmt.Println(results[0].I32()) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 6765 ``` `WithMaxModuleBytes` rejects oversized input before compilation. `WithMemoryLimitPages` caps the live size of each linear memory. `WithInstanceLimits` bounds simultaneously live direct instances; a closed instance returns its admission budget. `Policy` is an admission check against the module's declared capabilities and limits. The zero policy is permissive. A non-empty `AllowedCapabilities` list is exclusive, and `DeniedCapabilities` always wins. A `MaxMemoryBytes` policy also requires the module to declare a finite maximum. ## Handle cancellation and failures `Call` returns `context.Canceled` or `context.DeadlineExceeded` when its context interrupts guest execution: ```go if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("guest exceeded its deadline: %w", err) } ``` Policy failures wrap `wago.ErrPermissionDenied`. Runtime traps can be inspected without matching error text: ```go var trap *wago.TrapError if errors.As(err, &trap) { log.Printf("guest trapped: %s", trap.Code) } ``` A context can interrupt Wasm execution, but it cannot forcibly make arbitrary Go code return. Host functions that may block should accept a bounded dependency or cooperate with cancellation. Truly hostile blocking code needs process isolation. --- Source page: https://docs.wago.sh/beta/guides/embed/runtime-and-modules Markdown: https://docs.wago.sh/raw/beta/guides/embed/runtime-and-modules.md # Run WebAssembly from Go Start here when Wago should live inside your Go process. You will build the same guest in WAT, AssemblyScript, or TinyGo, then compile it, create an instance, and call its `add` export from Go. ## Create a small project You need Go 1.22 or newer and one guest compiler: [WABT](https://github.com/WebAssembly/wabt), [AssemblyScript](https://www.assemblyscript.org/getting-started.html), or [TinyGo](https://tinygo.org/getting-started/install/). ```sh mkdir wago-embed cd wago-embed go mod init example.com/wago-embed go get github.com/wago-org/wago@main mkdir guest ``` Pick a guest language. Each version exports the same WebAssembly function. ### WAT Create `guest/add.wat`: ```wat (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) ``` Build it: ```sh wat2wasm guest/add.wat -o module.wasm ``` ### AssemblyScript Create `guest/add.ts`: ```ts export function add(a: i32, b: i32): i32 { return a + b; } ``` Build it with a pinned compiler: ```sh npx --yes --package assemblyscript@0.28.8 asc \ guest/add.ts --runtime stub --optimize --noAssert \ --outFile module.wasm ``` ### TinyGo Create `guest/main.go`: ```go //go:build tinygo package main //go:wasmexport add func add(a, b int32) int32 { return a + b } func main() {} ``` Build it: ```sh tinygo build -target=wasm-unknown -no-debug \ -o module.wasm ./guest ``` Create `main.go`: ```go package main import ( "context" "fmt" "log" "os" "slices" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("module.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer instance.Close() // TinyGo reactors initialize their runtime through this export. WAT and // AssemblyScript modules in this example do not emit it. if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeValues(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeValues( ctx, "add", wago.ValueI32(20), wago.ValueI32(22), ) if err != nil { return err } fmt.Println(results[0].I32()) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` Run it: ```sh go run . ``` ```text 42 ``` The guest language changes how you produce `module.wasm`, not how you embed it. The Go side sees the same WebAssembly types and export name in every case. TinyGo's `_initialize` export is the one lifecycle difference in this example; call it once per new instance before calling your own exports. ## Know what you own `Runtime` owns shared compiler resources, plugins, and lifecycle state. `Module` holds validated native code that can be reused. `Instance` owns mutable guest state such as memory, tables, and globals. Create the runtime and compile the module once. Create instances according to the lifetime of the guest state you need, and close all three resources when you are finished. From here, choose the part your application needs: - [Calls and state](./calls-and-state) for values, memory, globals, and instance lifetime. - [Host functions](./host-functions) when Wasm needs to call your Go code. - [Limits and cancellation](./limits-and-policy) before running untrusted modules. - [Concurrency and shutdown](./services-and-concurrency) for a long-lived service. - [Precompiled artifacts](./artifacts) when startup compilation is too expensive. --- Source page: https://docs.wago.sh/beta/guides/embed/services-and-concurrency Markdown: https://docs.wago.sh/raw/beta/guides/embed/services-and-concurrency.md # Run Wago in a service Compile during service startup, then give each concurrent request its own instance. The requests share native code while keeping guest memory, tables, and globals isolated. Use the `fib.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "errors" "fmt" "log" "os" "sort" "sync" "time" "github.com/wago-org/wago" ) type Service struct { runtime *wago.Runtime module *wago.Module } func NewService(wasm []byte) (*Service, error) { runtime := wago.NewRuntime() module, err := runtime.Compile(wasm) if err != nil { _ = runtime.Close() return nil, err } return &Service{runtime: runtime, module: module}, nil } func (s *Service) Fib(ctx context.Context, value int32) (int32, error) { instance, err := s.runtime.Instantiate(ctx, s.module) if err != nil { return 0, err } defer instance.Close() results, err := instance.InvokeValues(ctx, "fib", wago.ValueI32(value)) if err != nil { return 0, err } return results[0].I32(), nil } func (s *Service) Close(ctx context.Context) error { return errors.Join(s.module.Close(), s.runtime.CloseContext(ctx)) } type response struct { line string err error } func run() error { wasm, err := os.ReadFile("fib.wasm") if err != nil { return err } service, err := NewService(wasm) if err != nil { return err } defer func() { _ = service.Close(context.Background()) }() jobs := []int32{10, 20, 30} responses := make(chan response, len(jobs)) var group sync.WaitGroup for _, value := range jobs { group.Add(1) go func() { defer group.Done() result, err := service.Fib(context.Background(), value) responses <- response{ line: fmt.Sprintf("fib(%d) = %d", value, result), err: err, } }() } group.Wait() close(responses) var lines []string for result := range responses { if result.err != nil { return result.err } lines = append(lines, result.line) } sort.Strings(lines) for _, line := range lines { fmt.Println(line) } shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() return service.Close(shutdown) } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` ```sh go run . go test -race ./... ``` ```text fib(10) = 55 fib(20) = 6765 fib(30) = 832040 ``` An individual instance accepts one call at a time. Create a fresh instance per request when state should not survive. If state must persist, assign that instance to one worker and serialize access to it. At shutdown, stop admitting requests, wait for active calls, close persistent instances, close modules, and then call `Runtime.CloseContext`. `Runtime.Close` starts shutdown and may finish asynchronously when callbacks or active work are involved; use `CloseContext` when the service must wait for the final result. --- Source page: https://docs.wago.sh/beta/guides/plugin-authoring Markdown: https://docs.wago.sh/raw/beta/guides/plugin-authoring.md # Author Wago plugins A Wago plugin is a Go package linked into a generated runtime. It can define host imports, observe or intercept runtime work, manage instances, transform modules, extend the compiler, or provide a typed service to another plugin. Start small. One definition, one provider, and one useful registration are enough for a real plugin. ## Start here ### [Write your first plugin](./plugins/authoring/first-plugin) Scaffold a module, define one host import, generate its catalog, and test it. ### [Definitions and providers](./plugins/authoring/definitions-and-providers) Describe what the plugin is, what it needs, and how Wago creates it. ### [Testing](./plugins/authoring/testing) Check definitions, registration, catalog drift, and clean installation. ### [Publish](./plugins/publish) Tag an open-source module and send its verified snapshot to the registry. ## Pick one next step - To give Wasm a function, read [Host imports](./plugins/authoring/host-imports). - To call it from a guest, compare [WAT, AssemblyScript, and TinyGo](./plugins/authoring/guest-languages). - To own work or observe calls, read [Lifecycle and hooks](./plugins/authoring/lifecycle-and-hooks). - To accept settings, read [Configuration](./plugins/authoring/configuration). - To connect plugins, read [Contracts and dependencies](./plugins/authoring/contracts). - To extend compilation, start with [Custom instructions](./plugins/authoring/custom-instructions), then [Custom types](./plugins/authoring/custom-types). Each privileged handle needs an exact publisher-authored Authority request and a consumer-reviewed grant. If your plugin only needs a host import, do not ask for instance management or runtime hooks. ## Trust boundary Plugins run as native Go code in the host process. Authorities limit access to Wago's privileged integration APIs; they do not sandbox file access, network access, process state, or other Go behavior. Keep the source public, keep dependencies narrow, and review plugins as native dependencies. The complete runnable set lives in [Wago's examples directory](https://github.com/wago-org/wago/tree/main/examples). --- Source page: https://docs.wago.sh/beta/guides/plugins Markdown: https://docs.wago.sh/raw/beta/guides/plugins.md # Use plugins This tutorial adds a plugin to a local Wago project and keeps the result reproducible. Use your own `module.wasm`; the plugin you choose must provide the imports or runtime features that module needs. The workflow is: ```text Project → add plugin → review access → build runtime → run module ``` Plugins are Go packages compiled into the Wago runtime. Review them as native dependencies, even when their requested Wago Authorities are narrow. ## Follow the tutorial - [Create a local project and add a plugin](./plugins/install-and-scope). - [Review the dependency graph, grants, and lockfile](./plugins/grants-and-lockfiles). - [Run the module, update the plugin, and rebuild from the lockfile](./plugins/update-and-rebuild). At the end, the project has a reviewed plugin runtime, a manifest that records what you requested, and a lockfile that can reproduce the exact build. Browse available packages at [plugins.wago.sh](https://plugins.wago.sh). --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/configuration Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/configuration.md # Configure a plugin Configuration lives in the reviewed lock entry. The definition describes its shape; the plugin reads the selected value. ## Define the Go shape ```go type Config struct { Prefix string `json:"prefix"` SampleRate int `json:"sampleRate"` } ``` ## Publish a schema Set `PluginDefinition.ConfigSchema` to a JSON Schema. Reject unknown fields and bound numbers and strings where you can. ```go ConfigSchema: json.RawMessage(`{ "type":"object", "additionalProperties":false, "properties":{"prefix":{"type":"string","maxLength":32}} }`), ``` Use `PluginProvider.ValidateConfig` only for rules the schema cannot express, such as a relationship between two fields. ## Read the value ```go var cfg Config if err := reg.Config(&cfg); err != nil { return err } ``` `Config` rejects unknown struct fields and trailing JSON. Apply defaults after decoding so they stay visible in code. The complete flow is in [examples/09-plugin-config-lifecycle](https://github.com/wago-org/wago/tree/main/examples/09-plugin-config-lifecycle). ## Change configuration Let Wago prompt for the new value: ```sh wago plugin config github.com/acme/wago-metrics ``` Wago validates and rebuilds before replacing project state. Review the resulting `wago-lock.json` change. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/contracts Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/contracts.md # Contracts and dependencies Use a Contract when one plugin needs a Go service from another. ## Name the service Put the interface and Contract value in a small package both plugins import: ```go type Clock interface { UnixMillis() int64 } var Contract = plugin.NewContract[Clock]( "github.com/acme/wago-clock/service", 1, ) ``` Change the major when providers and consumers can no longer share the same Go interface. ## Provide it List `Contract.Spec()` in `PluginDefinition.Provides`. During registration, provide the value: ```go return plugin.Provide(reg, Contract, clock) ``` ## Require it List the provider under `PluginDefinition.Requires` and the Contract under `Consumes`. Then get the typed reference: ```go clock, err := plugin.Require(reg, Contract) ``` Use the service only inside `With`: ```go return clock.With(func(service Clock) error { fmt.Println(service.UnixMillis()) return nil }) ``` `With` keeps the provider alive until the callback returns. Do not retain `service` after it returns. ## Choose a binding Use `plugin.Require` when exactly one provider must exist. Use `plugin.Optional` when the consumer can work without one. Use `plugin.Many` when it needs every selected provider in the reviewed order. The lockfile records exact providers and ordering. Wago rejects missing providers, incompatible majors, duplicate single bindings, unreviewed bindings, and cycles before it calls a plugin factory. Run [examples/13-plugin-contracts](https://github.com/wago-org/wago/tree/main/examples/13-plugin-contracts) for the complete two-plugin graph. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/custom-instructions Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/custom-instructions.md # Add a custom instruction A custom instruction starts as an ordinary function import. Wago replaces calls to that import while compiling the guest. ## Pick the guest ABI This WAT import carries two four-bit values through normal `i32` parameters: ```wat (import "wago:instr/example.int" "i4.add" (func $i4.add (param i32 i32) (result i32))) ``` Any language that can emit the same import can use it. ## Request the module Request `compiler.instruction.define` with `wago:instr/example.int` in `Scope.Modules`. ## Define its meaning Get `Registrar.CompilerInstructions`, then define the logical widths and portable handler: ```go Input: []int32{4, 4}, Output: []int32{4}, Handler: func(_ wago.InstructionContext, in []wago.Bits) ([]wago.Bits, error) { value, err := wago.BitsFromUint32(4, in[0].Uint32()+in[1].Uint32()) return []wago.Bits{value}, err }, ``` The handler is the fallback and the executable definition of the operation. ## Add a scalar lowering ```go Lower: func(ctx wago.LoweringContext) error { ctx.Output(0, ctx.Add(ctx.Input(0), ctx.Input(1))) return nil }, ``` Wago can inline this recipe on supported backends. The portable handler remains available elsewhere. Use target-specific code generation only when the scalar recipe cannot express the operation. Raw AMD64 or ARM64 emission is trusted backend code and needs architecture-tagged files. Run [examples/18-custom-instruction](https://github.com/wago-org/wago/tree/main/examples/18-custom-instruction) for the complete plugin and WAT guest. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/custom-types Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/custom-types.md # Add a custom compiler type Custom types keep plugin-owned values in native registers across a chain of custom instructions. The guest still uses a standard Wasm type such as `externref` for validation. ## Register the type Request `compiler.type.define` for the `example.value` namespace, then define the value: ```go value, err := types.Define(wago.CustomTypeSpec{ Name: "example.value/v256", Size: 32, Carrier: wago.WasmExternRef, }) ``` The size must be positive and 16-byte aligned. ## Use the returned token Add the token to a custom instruction signature: ```go Custom: &wago.CustomSignature{ Inputs: []wago.CustomType{value, value}, Output: &value, }, ``` The token belongs to that compiler registry. It cannot be forged or moved to another registry. ## Provide native code A custom value has no portable handler. Add target-specific lowerings in `codegen_amd64.go` and `codegen_arm64.go`. The lowering receives and returns the native register bundle through `InputCustom` and `OutputCustom`. Custom values currently have expression lifetime. They can flow directly between custom calls or be dropped. They cannot enter Wasm locals, cross control flow, pass to ordinary functions, or return from the guest. Run [examples/19-custom-type](https://github.com/wago-org/wago/tree/main/examples/19-custom-type). Its WAT guest uses `externref`; the plugin keeps the 256-bit value in one AMD64 YMM register or two ARM64 vector registers. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/definitions-and-providers Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/definitions-and-providers.md # Definitions and providers Every plugin has an immutable definition and an explicit provider. Wago can review and resolve the definition without constructing the plugin. ## `PluginDefinition` The definition is published metadata, not runtime state. Give it a canonical `ID`, a semantic `Version`, and clear registry text through `Name`, `Description`, and `Stability`. Record where the code came from in `Provenance`, and use `Compatibility` to state which Wago versions and platforms it supports. Add `Requires` for plugin dependencies, `Authorities` for privileged Wago APIs, `ConfigSchema` for user configuration, and `Provides` or `Consumes` for typed Contracts. Leave out sections the plugin does not need. The definition must contain enough information to review the plugin before its code is downloaded or run. Keep reasons concrete: `define the acme_clock guest API` is useful; `needed by the plugin` is not. ## `PluginProvider` The provider connects metadata to code: ```go func Provider() wago.PluginProvider { return wago.PluginProvider{ Definition: Definition, New: func() wago.Plugin { return &plugin{} }, ValidateConfig: validateConfig, } } ``` `New` must return a new plugin value suitable for one runtime load. Put per-runtime mutable state on that value instead of package globals. `ValidateConfig` is optional and handles semantic checks that the published schema cannot express. ## The `/register` catalog A module exposes its providers through a conventional package: ```go // Package register exposes this module's Wago providers. package register func Providers() []wago.PluginProvider { return []wago.PluginProvider{ clock.Provider(), metrics.Provider(), } } ``` Generated runtimes import `/register` and combine its returned values. Do not use `init` to register providers. Hidden global registration makes selection depend on import side effects and prevents an empty runtime from staying empty. One Go module may publish several providers. Give each provider its own canonical ID and version, then return all of them from the root catalog. Use package dependencies when selecting one provider must also select another. ## Keep versions aligned Before a release, these values must agree: - `package.version` in `wago.json`; - every published `PluginDefinition.Version` for that release; - the Git tag, such as `v0.2.0`; and - the committed `wago.providers.json` snapshot. Publication rejects mismatched tagged metadata. Move to a new version instead of rewriting an existing tag. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/first-plugin Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/first-plugin.md # Write your first plugin This plugin adds `tutorial.answer() -> i32` and returns `42`. You need Go 1.22 or newer and a standard Wago runtime. ## Start the wizard ```sh mkdir wago-answer cd wago-answer wago init --plugin ``` Answer the prompts. The wizard writes the manifest, provider catalog, Go package, and first test. > **Info — Canary dependency:** If Go reports that `github.com/wago-org/wago@v0.1.0` does not exist yet, point the scaffold at current canary source: ```sh go mod edit -droprequire github.com/wago-org/wago go get github.com/wago-org/wago@main ``` ## Request one Authority Open `register/register.go`. Add this request to the generated definition: ```go Authorities: []wago.AuthorityRequest{{ Name: wago.AuthorityHostImportDefine, Mode: wago.AuthorityRequired, Reason: "define the tutorial guest API", Scope: wago.AuthorityScope{Modules: []string{"tutorial"}}, }}, ``` The scope covers the exact import module `tutorial`. It does not cover parent names or wildcards. ## Define the guest function Inside `Register`, get the reviewed module: ```go imports, err := reg.HostImports() if err != nil { return err } ``` Then add the function: ```go imports.HostFunc("tutorial", "answer", func() int32 { return 42 }) return nil ``` Wago infers this function's no-parameter, one-`i32` signature. ## Check it Format the file: ```sh gofmt -w register/register.go ``` Refresh the published definition snapshot: ```sh wago plugin catalog ``` Run the tests: ```sh go test ./... ``` Check that the snapshot is current: ```sh wago plugin catalog --check ``` ![Generating and checking a Wago plugin catalog](/demos/plugin-authoring.gif) The complete runnable version is [examples/08-custom-plugin](https://github.com/wago-org/wago/tree/main/examples/08-custom-plugin). Next, read [Definitions and providers](./definitions-and-providers). --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/guest-languages Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/guest-languages.md # Call a plugin from guest code Plugin imports are ordinary Wasm functions. Use the syntax your guest language already provides for imported functions. This example calls `tutorial.answer() -> i32`. ### WAT ```wat (import "tutorial" "answer" (func $answer (result i32))) (func (export "run") (result i32) call $answer) ``` ### AssemblyScript ```ts @external("tutorial", "answer") declare function answer(): i32; export function run(): i32 { return answer(); } ``` ### TinyGo ```go //go:wasmimport tutorial answer func answer() int32 //go:wasmexport run func run() int32 { return answer() } ``` The module name, function name, parameters, and results must match the plugin declaration. Run [examples/22-language-guests](https://github.com/wago-org/wago/tree/main/examples/22-language-guests) to execute all three compiled guests against one host function. Its build script reproduces the checked-in `.wasm` files. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/host-imports Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/host-imports.md # Add host imports A host import is a Go function called by Wasm. The plugin's `host.import.define` grant names the exact import modules it may add. ## Get the registrar ```go imports, err := reg.HostImports() if err != nil { return err } ``` Return `err` before registering functions. A grant for `acme_math` does not cover a parent, child, or wildcard name; flat registration preserves the exact module and function identity. ## Write the callback ```go func addOne(value int32) int32 { return value + 1 } ``` Ordinary supported Go signatures are inferred without runtime reflection. Use `func(wago.HostCall)` for arbitrary supported scalar/reference arity, or `func(wago.Caller, wago.HostCall)` when the callback needs guest state. ## Declare its Wasm signature ```go imports.HostFunc("acme_math", "add_one", addOne). Params(wago.ValI32). Results(wago.ValI32) ``` Wago checks that signature against the importing module. ## Guest memory `Caller.Memory()` returns memory 0 for the duration of a caller-aware callback. Check the range before slicing and do not retain the slice, `Caller`, or `HostCall`. ```go memory := caller.Memory() offset := uint64(uint32(call.I32(0))) if offset >= uint64(len(memory)) { return } ``` Use `GuestStorageHostModule` for indexed memory, Memory64 metadata, exact GC types, or Wasm GC arrays. [examples/21-guest-storage](https://github.com/wago-org/wago/tree/main/examples/21-guest-storage) shows the checked borrow. ## Guest capabilities Register a capability when the import gives Wasm a permission the host may deny: ```go err := reg.GuestCapability( wago.Capability("clock.read"), wago.CapabilityDocs("read the host clock"), ) ``` The guest capability governs Wasm. The Plugin Authority governs trusted Go plugin code. Run [examples/08-custom-plugin](https://github.com/wago-org/wago/tree/main/examples/08-custom-plugin) for a complete import and capability. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/lifecycle-and-hooks Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/lifecycle-and-hooks.md # Lifecycle and hooks `Register` builds a plan. It should decode configuration and declare contributions, without starting work that must later be undone. ## Add lifecycle callbacks Keep the registration small: ```go return reg.Lifecycle(wago.PluginLifecycle{ Start: p.start, Stop: p.stop, }) ``` Both callbacks receive a `context.Context` and return an error. `Start` runs after Wago accepts the full plugin plan. Start listeners, files, and goroutines there. `Stop` also runs after a partially failed `Start`. Check which resources exist, stop accepting work, wake blocked callbacks, and release each resource once. See [examples/09-plugin-config-lifecycle](https://github.com/wago-org/wago/tree/main/examples/09-plugin-config-lifecycle) for a runnable lifecycle. ## Choose a hook Use `RuntimeCloseObserver` when runtime shutdown matters. Module work belongs in `ModuleSourceTransformer`, `ModuleCompileObserver`, or `ModuleCloseObserver`. Their Authorities are `runtime.close.observe`, `module.source.transform`, `module.compile.observe`, and `module.close.observe`. For instances, an interceptor can reject work or attach state; an observer records the result. Use `InstanceInstantiateInterceptor` or `InstanceInstantiateObserver` while creating an instance, and `InstanceInvokeInterceptor` or `InstanceInvokeObserver` around calls. `InstanceCloseObserver` handles exact-instance close. Request only the matching Authority: `instance.instantiate.intercept`, `instance.instantiate.observe`, `instance.invoke.intercept`, `instance.invoke.observe`, or `instance.close.observe`. ## Observe a call Get the observer during registration: ```go calls, err := reg.InstanceInvokeObserver() if err != nil { return err } ``` Attach the callback: ```go return calls.After(func(event wago.InvocationEvent) { log.Printf("%s: %v", event.Export, event.Err) }) ``` Observers record outcomes. Interceptors may return an error to stop an operation. Use opaque event identities to correlate state instead of retaining a `Runtime`, `Module`, or `Instance`. Run [examples/10-hooks](https://github.com/wago-org/wago/tree/main/examples/10-hooks) to see the complete compile, instantiate, invoke, close, and runtime-close order. --- Source page: https://docs.wago.sh/beta/guides/plugins/authoring/testing Markdown: https://docs.wago.sh/raw/beta/guides/plugins/authoring/testing.md # Test a plugin Test one boundary at a time. Most plugin mistakes appear before a Wasm module runs. ## Test ordinary Go code ```sh go test ./... ``` Keep parsing, state, and service logic outside `Register`. Then those parts need no Wago test setup. If callbacks share state, run: ```sh go test -race ./... ``` ## Test registration Build a `PluginSet` with the same definition, grants, configuration, dependencies, and Contract bindings a consumer will review. Then validate it: ```go if err := wago.ValidatePluginSet(reviewedSet()); err != nil { t.Fatal(err) } ``` Add a case for each optional Authority you can run without. Add a scope-boundary case for modules or instance budgets. The runnable examples use [examples/internal/exampleplugin](https://github.com/wago-org/wago/tree/main/examples/internal/exampleplugin) to keep this setup out of each `main.go`. ## Check the catalog After changing a definition, refresh its snapshot: ```sh wago plugin catalog ``` CI should only check for drift: ```sh wago plugin catalog --check ``` Commit `wago.providers.json` with the code it describes. ## Test shutdown For a plugin with lifecycle work, cover: - normal `Start` and `Stop`; - a partially completed `Start`; - cancellation during startup; - an active callback during close; and - release of every plugin-owned resource. Use a deadline for tests that wait on goroutines. ## Try the consumer path Push a test version, then use a new directory: ```sh mkdir consumer-test cd consumer-test wago init --run ``` Add the plugin interactively: ```sh wago add github.com/acme/wago-answer ``` Read the review Wago shows, run a small guest, and rebuild once from the lockfile: ```sh wago plugin rebuild --locked ``` A clean directory catches missing release files and accidental module-cache dependencies. --- Source page: https://docs.wago.sh/beta/guides/plugins/faq Markdown: https://docs.wago.sh/raw/beta/guides/plugins/faq.md # Plugin FAQ ### Do I need a plugin for every Wasm module? No. Modules that only use core WebAssembly can run with the bare runtime. Inspect a module first: ```sh wago module imports module.wasm ``` Add a plugin when those imports or another runtime feature need one. ### Why does WASI come from a plugin? WASI is a host interface, not a core WebAssembly instruction set. Keeping it in a plugin lets a project choose the WASI version and capabilities it needs without adding them to every Wago runtime. ### Do plugins require Go? Yes. Wago compiles selected plugins into a project or global runtime. Install Go 1.22 or newer before adding or rebuilding plugins. ### Why does adding a plugin take longer than running a module? `wago add` resolves packages, checks definitions and grants, downloads Go modules, generates a runtime, and builds it. Later runs reuse that built runtime until the selected graph changes. ### Should I install a plugin locally or globally? Use local scope for a project you may share or deploy. Its manifest and lockfile travel with the repository. Use global scope for personal tools you want in unrelated directories. ### Are plugins sandboxed? No. Plugins are native Go dependencies in the host process. Authorities limit their access to privileged Wago handles, but ordinary Go code can still use the operating system and process APIs available to the host. ### What is an Authority? An Authority is one exact privileged Wago integration, such as defining imports in a named module or observing invocations. The publisher requests it with a reason and scope; the consumer reviews the grant during installation. ### What happens if I deny a required Authority? Wago leaves the previous runtime and project state in place. You can narrow a required scope, but registration fails if the plugin cannot work within that grant. Optional Authorities may be omitted. ### How are guest capabilities different from plugin Authorities? A plugin Authority controls what trusted Go plugin code may add to Wago. A guest capability controls what a Wasm module may use through the host. A filesystem plugin may need `host.import.define` while exposing `fs.read` and `fs.write` to guest policy. ### Why are there two JSON files? `wago.json` records direct project intent and version ranges. `wago-lock.json` records exact sources, checksums, definitions, grants, configuration, dependencies, and Contract bindings. Commit both for local projects. ### Can I edit wago-lock.json by hand? Do not edit digests, checksums, grants, or bindings to silence a failure. Use `wago add`, `wago plugin grant`, `wago plugin config`, `wago plugin update`, or `wago rm`, then review the generated diff. ### Why does a plugin expose a register package? Generated runtimes import `/register` and call `Providers()` to collect explicit provider values. Wago does not use hidden process-global registration from `init`. ### Can one repository publish several plugins? Yes. Give each provider a canonical package ID and immutable definition, then return the providers from the module's root catalog. The root package can also act as an aggregate that selects subpackages. ### Can a plugin add custom Wasm instructions? Yes. The guest imports an ordinary function, and a plugin with `compiler.instruction.define` supplies its semantics and compiler lowering. Start with [Custom instructions](./authoring/custom-instructions). ### What is a custom compiler type? It is a plugin-owned value that stays in native registers between custom instruction calls. The guest uses a standard carrier such as `externref`; no new Wasm binary type is required. See [Custom types](./authoring/custom-types). ### Which guest languages can use a plugin? Any language that can emit the plugin's ordinary Wasm imports. The examples include [WAT, AssemblyScript, and TinyGo](./authoring/guest-languages). ### Where does plugin configuration live? The selected JSON value lives in the plugin entry in `wago-lock.json`. Change it with `wago plugin config`; do not put plugin-owned settings under the core `settings` object in `wago.json`. ### When should two plugins use a Contract? Use a Contract when one plugin needs a typed Go service from another. Keep the interface small, give it a stable ID and incompatible major version, and access values only through the leased `With` callback. ### Does inspection run plugin code? `wago plugin inspect`, `wago plugin list --json`, and immutable plan inspection read definitions and reviewed selections without calling factories, `Register`, `Start`, or `Stop`. ### How do I test an unpublished plugin? Run normal Go tests, validate a `PluginSet` with `wago.ValidatePluginSet`, and check the generated catalog. The public CLI install path needs a published module release, so test that path from a clean project after pushing a test version. ### Can the public registry host a private plugin? No. Registry releases point to public source and are verified from the tagged Go module. An embedder can link its own provider catalog directly in Go, but that is a separate deployment path from registry installation. ### Why did a locked rebuild fail after an update? The manifest, module cache, provider catalog, definition, grant, configuration, or Contract binding no longer matches the committed graph. Run a networked update, review and commit the result, then retry `wago plugin rebuild --locked`. ### How do I remove a plugin? Run: ```sh wago rm github.com/acme/plugin ``` Wago removes transitive plugins that no other direct requirement needs and asks you to review any changed Contract bindings. --- Source page: https://docs.wago.sh/beta/guides/plugins/grants-and-lockfiles Markdown: https://docs.wago.sh/raw/beta/guides/plugins/grants-and-lockfiles.md # Review the install Adding the plugin created two files. `wago.json` records the plugin and version range you requested. `wago-lock.json` records the exact source, checksums, dependencies, grants, configuration, and Contract bindings Wago built. Commit both files. Review their diff whenever the plugin graph changes. ## Inspect the graph Show every direct and transitive plugin: ```sh wago plugin tree ``` Inspect one installed plugin: ```sh wago plugin inspect ``` Choose a plugin in the interactive picker. Check its repository, version, dependencies, requested Authorities, reasons, scopes, and Contract bindings. Inspection reads built metadata without starting plugin lifecycle code. An Authority grants access to one privileged Wago integration API. It does not sandbox the plugin's ordinary Go code. If the request is broader than the plugin's job, cancel the install or edit the grant: ```sh wago plugin grant ``` The interactive editor can narrow requested modules and resource limits or deny optional access. It cannot grant access the publisher did not request or widen a scope beyond that request. Next, [run the module and maintain the plugin runtime](./update-and-rebuild). --- Source page: https://docs.wago.sh/beta/guides/plugins/install-and-scope Markdown: https://docs.wago.sh/raw/beta/guides/plugins/install-and-scope.md # Add a plugin You need an active Wago runtime and Go 1.22 or newer. Complete [Getting started](../../getting-started) first if `wago status` does not show a runtime. Start in the directory that contains your `module.wasm`. Initialize a local project: ```sh wago init ``` Select **Run WebAssembly**. Wago creates `wago.json` in the current directory. Inspect the module before choosing a plugin: ```sh wago module imports module.wasm ``` Find a package that provides those imports at [plugins.wago.sh](https://plugins.wago.sh), then add it. For a module that imports Wide's `as-simd` functions: ```sh wago add JairusSW/wide ``` Review the source and requested access in the interactive security screen, then confirm the build. Wago leaves the old project state in place if resolution or compilation fails. The nearest `wago.json` makes this a local install. Local plugins travel with the project and are the right default for repositories you share or deploy. Global plugins are intended for personal tools used across unrelated directories. Confirm that the plugin was built: ```sh wago plugins list ``` Next, [review exactly what Wago installed](./grants-and-lockfiles). --- Source page: https://docs.wago.sh/beta/guides/plugins/publish Markdown: https://docs.wago.sh/raw/beta/guides/plugins/publish.md # Publish a Wago plugin Package a reusable Wago plugin, preview exactly what will ship, then publish it to the public plugin registry. New plugin authors should finish [Write your first plugin](./authoring/first-plugin) and [Test a plugin](./authoring/testing) before tagging a release. Publishing requires a public GitHub repository and a Wago registry account. The dry run works before login. ## Prepare the plugin ```sh wago init --plugin ``` Skip this command if the plugin already exists. The wizard collects the package metadata and creates the release files. A publishable manifest points to public source and keeps discovery metadata under `package`. Wago plugins are open source. Declare every privileged Wago integration as an exact Authority with a human reason and enforceable scope. Declare package requirements separately from typed, major-versioned Contracts. Provider catalogs return values from `Providers()`; they never self-register from `init`. ## Sign in ```sh wago auth login ``` ## Refresh the catalog ```sh wago plugin catalog ``` Run the plugin tests. Then check that no definition changed during the test run: ```sh wago plugin catalog --check ``` ## Commit and tag ```sh git add wago.json wago.providers.json register git commit -m "Prepare plugin v0.1.0" ``` Tag that commit and push it: ```sh git tag v0.1.0 git push origin HEAD v0.1.0 ``` The version in the tag, manifest, and definitions must match. ## Preview publication ```sh wago plugin publish --dry-run ``` ## Publish ```sh wago plugin publish ``` The publish dry run only prints the planned mutation. Actual publishing first checks the local catalog against the committed snapshot, then downloads the exact tagged Go module. Its `wago.json` package metadata and `wago.providers.json` must match the local release, and its `h1:` checksum is sent with the request. Local code runs only for the local drift check; Wago does not execute code from the downloaded tag. The registry independently downloads that same exact module and checksum, reads both artifacts without executing plugin code, and rejects any mismatch. Consumers later review the stored immutable definitions before plugin code is downloaded or built; linked definitions must match their reviewed digests. --- Source page: https://docs.wago.sh/beta/guides/plugins/update-and-rebuild Markdown: https://docs.wago.sh/raw/beta/guides/plugins/update-and-rebuild.md # Run and maintain the plugin Wago finds the nearest `wago.json` and uses its generated runtime automatically. Run your module: ```sh wago run module.wasm ``` If the module still reports a missing import, compare `wago module imports module.wasm` with `wago plugins list` and return to the plugin review. ## Check for updates ```sh wago plugin outdated ``` This does not change the project. To update the selected plugin graph: ```sh wago plugin update ``` Follow the same interactive review used during installation. Wago asks again when an update adds or widens access or changes Contract bindings. Review the `wago.json` and `wago-lock.json` diff before committing it. ## Rebuild from the lockfile ```sh wago plugin rebuild ``` This rebuilds the runtime from the exact versions, checksums, grants, configuration, and Contract bindings in `wago-lock.json`. ## Remove a plugin ```sh wago rm JairusSW/wide ``` Wago removes transitive dependencies that nothing else needs and asks you to review changed Contract bindings. The project is now portable: commit `wago.json` and `wago-lock.json`, then run `wago plugin rebuild` after cloning it elsewhere. See [Automation and Go](../../reference/configuration/automation-and-go) for non-interactive CI checks, or the [Plugin FAQ](./faq) for scopes, configuration, and troubleshooting. --- Source page: https://docs.wago.sh/beta/ Markdown: https://docs.wago.sh/raw/beta/index.md # Welcome to Wago Glad you're here! ## What is Wago? Wago is a wonderfully quick, compact, and extensible WebAssembly runtime for Go. A quote has stuck with me throughout the project: > “Fast hardware should bring excellence, not reason to waste it.” We built Wago around this idea. Because of it, we pushed to cut overhead, memory use, and bloat instead of hiding them behind faster hardware. Our goal is to make Wago as fast and capable as possible without ever letting it grow wasteful. The community should shape Wago too. Its plugin system lets users supply imports, control code generation, and even add custom WebAssembly features. Plugins can take Wago in new directions without forcing every new idea into the core runtime. ## What's in the box? We wanted Wago to be wonderful to use, so we've actually added quite a bit. - **Runtime and compiler**: execute Wasm, save precompiled `.wago` files, or build standalone executables for AMD64 and ARM64. - **Plugins**: extend the runtime with literally anything. Host capabilities, compiler hooks, and custom WebAssembly features all fit here. - **Manager**: install, swap, and update Wago runtimes across beta, canary, or a specific commit. - **Registry**: discover and publish extensions at [plugins.wago.sh](https://plugins.wago.sh). - **Go API**: compile once, create isolated instances, call typed exports, access guest state, and honor cancellation inside your own process. ## Digging in ### [Run a Wasm file](./getting-started) Install Wago, choose a runtime, and run a real module before moving on to the full CLI guide. ### [Embed Wago in Go](./guides/embed/runtime-and-modules) Keep a runtime in your process, reuse compiled modules, and create isolated guest instances. ### [Connect Wasm to Go](./guides/embed/host-functions) Bind reflection-free host functions and exchange values through checked guest memory. ### [Extend Wago with plugins](./using-plugins) Add WASI and run your first module with host capabilities, then explore the full plugin system. --- Source page: https://docs.wago.sh/beta/reference/configuration Markdown: https://docs.wago.sh/raw/beta/reference/configuration.md # Configuration Wago layers configuration from broad defaults to one command: 1. Runtime defaults. 2. User-wide configuration. 3. Project settings in `wago.json`. 4. Explicit command flags. ## Pick a topic ### [Scopes and settings](./configuration/scopes-and-settings) Inspect, set, reset, and preview stable or experimental values. ### [Project manifest](./configuration/project-manifest) Configure features, optimizations, workers, and project plugins in `wago.json`. ### [Automation and Go](./configuration/automation-and-go) Isolate state, install completions, use locked modes, and configure the Go API. --- Source page: https://docs.wago.sh/beta/reference/configuration/automation-and-go Markdown: https://docs.wago.sh/raw/beta/reference/configuration/automation-and-go.md # Configure CI, shells, and the Go API Keep automation isolated from your normal Wago install, remove prompts from scripts, add shell completions, and set runtime policy from Go. ## Isolate Wago state Set `WAGO_HOME` to place manager configuration, installed runtimes, and caches under one root: ```sh WAGO_HOME="$PWD/.wago-ci" wago version current ``` Give concurrent CI jobs separate directories. Inspect paths rather than guessing: ```sh wago status --json wago version which wago cache dir ``` ## Automation flags | Flag | Meaning | |---|---| | `--no-input` | Never prompt; fail if input is missing | | `--dry-run` | Show a supported mutation plan | | `--json` | Emit machine-readable output where supported | | `--locked` | Refuse manifest or lockfile changes | | `--offline` | Use installed and cached resources only | For a prepared repeatable build: ```sh wago run --locked --offline --invoke fib fib.wasm 20 ``` Describe the command surface programmatically: ```sh wago commands --json ``` ## Shell completions ```sh wago config completions zsh wago config completions zsh --install ``` Use `--output` for a specific completion file and `--rc` for a particular startup file. Preview installation with `--dry-run`. ## Go API Use `RuntimeConfig` for compiler policy and `WithPolicy` for per-instance guest limits. The runnable configuration example is in [Create runtimes and modules](../../guides/embed/runtime-and-modules). --- Source page: https://docs.wago.sh/beta/reference/configuration/project-manifest Markdown: https://docs.wago.sh/raw/beta/reference/configuration/project-manifest.md # Configure `wago.json` `wago.json` combines sparse project runtime settings with plugin requirements: ```json { "$schema": "https://wago.sh/v1/schema.json", "settings": { "features": { "simd": true }, "optimizations": { "inline-loop-callees": false }, "runtime": { "parallel": "auto", "deferredBoundsChecking": true } }, "plugins": { "github.com/wago-org/wasi": "^0.1.0" } } ``` Add the schema URI for editor completion and typo detection. The draft-2020-12 schema rejects unknown fields. Create a minimal project: ```sh wago init --run ``` ## Feature settings `settings.features` enables or disables WebAssembly feature families. The runtime defaults to its supported Core 3 feature set; `--core 2` selects the narrower Core 2 compatibility profile for commands that expose it. Use individual settings when a project needs a narrower feature policy. ## Optimization settings ```json { "settings": { "optimizations": { "inline": false } } } ``` The names match CLI switches such as `--no-inline`. Architecture-specific optimizations may not exist on another target. ## Runtime settings `settings.runtime.parallel` accepts `"auto"` or a non-negative worker count encoded as a string. - `"auto"` uses adaptive work. - `"1"` forces serial function work. - A larger number sets a maximum. `deferredBoundsChecking` controls whether Wago may omit explicit checks already proven redundant. ## Plugins and lockfile state `plugins` maps canonical Go module or package paths to semantic-version ranges. Exact direct and transitive sources, checksums, release fingerprints, definition digests, dependency edges, requested and granted Authorities, Contract bindings, and opaque plugin configuration belong in `wago-lock.json`. Ranges support exact, comparator, caret, tilde, partial/x, hyphen, intersection, and `||` union forms. Relative aliases are invalid: use `github.com/wago-org/wasi`, not `wago-org/wasi`. Commit both files. Keep plugin configuration out of `settings`; it belongs to the plugin's reviewed lock entry. ## Publish metadata When the manifest describes a publishable plugin, public metadata lives under a `package` object: ```json { "$schema": "https://wago.sh/v1/schema.json", "package": { "module": "github.com/acme/wago-observability", "version": "0.1.0", "name": "Wago Observability", "description": "Tracing and metrics for Wago runtimes.", "license": "Apache-2.0", "repository": "https://github.com/acme/wago-observability", "authors": [ { "name": "Example Maintainer", "github": "example" } ] } } ``` Provider definitions, Authorities, configuration schemas, and Contracts are not duplicated by hand in this file. Publishing obtains them from the module's explicit `/register` catalog and stores their canonical digests beside the release. The committed module-root `wago.providers.json` is the immutable catalog snapshot. Generate it with `wago plugin catalog`, verify it in CI with `wago plugin catalog --check`, and commit it before creating the release tag. It uses `https://wago.sh/v1/providers.schema.json`. See [Publish a plugin](../../guides/plugins/publish) for the complete workflow. --- Source page: https://docs.wago.sh/beta/reference/configuration/scopes-and-settings Markdown: https://docs.wago.sh/raw/beta/reference/configuration/scopes-and-settings.md # Configure global and project settings Inspect the effective value first, then decide whether the change belongs to the whole machine or only the current project. ## Inspect effective configuration ```sh wago config wago config list wago config list --json wago config diff ``` Inside a project, configuration commands use local scope by default. Be explicit in scripts: ```sh wago config list --local wago config list --global ``` ## Get and set one value ```sh wago config get optimizations.inline wago config set optimizations.inline off --local wago config set optimizations.inline on --global ``` Boolean values accept `on`/`off`, `true`/`false`, `yes`/`no`, and `1`/`0`. ## Reset inheritance ```sh wago config reset optimizations.inline --local wago config reset --all --local ``` Resetting a local value removes the override. The project inherits the global value again. ## Precedence --- Source page: https://docs.wago.sh/beta/troubleshooting Markdown: https://docs.wago.sh/raw/beta/troubleshooting.md # Troubleshooting Most failures happen at a boundary. Start by recording the selected manager, runtime, project, plugins, and module requirements: ```sh wago --version wago status wago version current wago version which ``` ## Pick the failing boundary ### [Installation and runtimes](./troubleshooting/installation-and-runtimes) Fix `PATH`, missing runtimes, wrong variants, and stale compiled artifacts. ### [Modules and calls](./troubleshooting/modules-and-calls) Diagnose validation, missing imports, exports, arguments, and feature sets. ### [Plugins and builds](./troubleshooting/plugins-and-builds) Separate plugin resolution, authorization, lockfile, and standalone build failures. ### [Go API and memory](./troubleshooting/go-api-and-memory) Fix host signatures, pointer-length checks, cancellation, and instance use. ## Report an issue Include the exact command, complete error, OS, architecture, selected runtime, module SHA-256, and the smallest module that reproduces it. Open an issue at [github.com/wago-org/wago/issues](https://github.com/wago-org/wago/issues). --- Source page: https://docs.wago.sh/beta/troubleshooting/go-api-and-memory Markdown: https://docs.wago.sh/raw/beta/troubleshooting/go-api-and-memory.md # Fix Go API and guest memory problems Start at the host-to-Wasm boundary: import signatures, checked memory ranges, context cancellation, and instance ownership. ## Host import mismatch Create imports with `wago.NewImports()` and register callbacks with `imports.HostFunc(module, name, fn)`. Module and function names remain separate exact identities. Wago checks the callback and declared signature before guest startup. Inspect the module first: ```sh wago module imports fib.wasm ``` Then compare the parameter and result slots with the guest declaration. ## Guest memory range failure Treat pointers as offsets. Validate addition in a wider integer: ```go end := uint64(ptr) + uint64(length) if end > uint64(len(memory)) { return fmt.Errorf("out of bounds") } data := memory[uint64(ptr):end] ``` Outside host callbacks, prefer checked instance helpers: ```go data, ok := inst.Read(ptr, length) if !ok { return fmt.Errorf("out of bounds") } ``` `Caller.Memory()`, `HostCall`, and its raw slot views are valid only during that synchronous callback. Copy bytes that must survive it. ## Cancellation does not stop work Use a context-aware call: ```go out, err := inst.InvokeValues(ctx, "work", args...) ``` or the low-level form: ```go out, err := inst.InvokeContext(ctx, "work", slots...) ``` The context needs a deadline or cancel function, and the same context must reach Wago. Blocking Go work in a host function needs separate cancellation. ## Concurrent instance calls One instance cannot execute simultaneous public calls. Create separate instances from the same compiled module for parallel guest work. ## Report a reduced failure Include the exact command or Go call, complete error, selected runtime, OS, architecture, module hash, and the smallest reproducer. For memory bugs, include the pointer, length, memory size, and guest signature. --- Source page: https://docs.wago.sh/beta/troubleshooting/installation-and-runtimes Markdown: https://docs.wago.sh/raw/beta/troubleshooting/installation-and-runtimes.md # Fix installation and runtime selection Use this page when the shell cannot find Wago, no runtime is active, the wrong build is selected, or a cached artifact became stale. ## The shell cannot find `wago` If installation finished moments ago, open a new terminal. Then locate the executable: ### macOS / Linux ```sh command -v wago ``` ### PowerShell ```powershell Get-Command wago ``` ### Command Prompt ```cmd where wago ``` If nothing appears, rerun the installer from [Getting started](../getting-started). If two paths appear, the first one wins; remove or reorder the stale entry. ## No runtime is active The manager intentionally does not bundle one: ```sh wago version install wago version current wago version which ``` Non-interactively: ```sh wago version install --canary --use --no-input ``` ## The wrong variant is active ```sh wago version switch canary --profile standard --build normal ``` `wago version current` reports version, profile, and build. ## A `.wago` file stopped loading Compiled artifacts are tied to Wago's format and the host architecture. Rebuild from the original Wasm: ```sh wago build fib.wasm -o fib.wago ``` Distribute `.wasm` for portability or use `wago compile` for a target-specific standalone executable. ## Inspect and clean caches ```sh wago cache dir wago cache size wago cache prune --yes ``` Use `wago cache clean` only when you intend to regenerate the selected data. --- Source page: https://docs.wago.sh/beta/troubleshooting/modules-and-calls Markdown: https://docs.wago.sh/raw/beta/troubleshooting/modules-and-calls.md # Fix module, import, export, and call errors Separate decoding, validation, linking, and invocation. The first boundary that fails tells you where to look next. ## Decode or validation failure Separate validation from execution: ```sh wago validate fib.wasm ``` Common causes are malformed bytes, a disabled proposal, a module built for a different WebAssembly feature profile, or a feature unavailable on the selected platform. Wago enables its supported Core 3 feature set by default. Select Core 2 compatibility when the producer or deployment requires that narrower profile: ```sh wago run --core 2 --invoke fib fib.wasm 20 ``` Do not use feature flags to force malformed Wasm through. ## Missing import ```sh wago module imports fib.wasm wago module capabilities fib.wasm ``` An unresolved import means the module needs another plugin scope, an uninstalled plugin, an application host function, or a corrected name and signature. For a local project: ```sh wago init --run wago add github.com/wago-org/wasi wago plugin list ``` For the Go API: ```go imports := wago.NewImports() imports.HostFunc("host", "log", logFunc) instance, err := runtime.Instantiate(ctx, module, wago.WithImports(imports)) ``` ## Missing export Command modules normally export `_start`. Select a library function explicitly: ```sh wago run --invoke missing fib.wasm 20 ``` A source-language function name does not necessarily survive compilation as a Wasm export. ## Rejected arguments Wago follows the Wasm signature. This fails before guest code because `nope` is not an `i32`: ```sh wago run --invoke fib fib.wasm nope ``` Use a value that matches the signature: ```sh wago run --invoke fib fib.wasm 30:i32 ``` In Go, use matching typed values: ```go out, err := inst.InvokeValues(ctx, "add", wago.ValueI32(20), wago.ValueI32(22)) ``` --- Source page: https://docs.wago.sh/beta/troubleshooting/plugins-and-builds Markdown: https://docs.wago.sh/raw/beta/troubleshooting/plugins-and-builds.md # Fix plugin resolution and standalone builds Inspect the selected scope and resolved plugin graph before changing grants, lockfiles, offline mode, or compiler settings. If you need a concept explained rather than an error diagnosed, start with the [Plugin FAQ](../guides/plugins/faq). ## Inspect plugin state ```sh wago status wago plugin tree wago plugin list --json wago plugin inspect github.com/wago-org/wasi wago plugin rebuild --locked ``` Then identify the failing stage: - If `wago.providers.json` is missing or stale, run `wago plugin catalog`, inspect the diff, and commit it before tagging. Use `wago plugin catalog --check` in CI. - If publish reports an exact-source mismatch, the tagged module's `wago.json` or `wago.providers.json` differs from the local release. Move the version forward and create a new tag after committing both artifacts; do not reuse a published Go module version. - `wago plugin outdated` checks for newer releases. - `wago plugin grant github.com/wago-org/wasi` edits reviewed Authority scope. - `wago plugin rebuild` reproduces locked versions. - `wago plugin update github.com/wago-org/wasi` changes resolution and rebuilds. Use `--verbose` when the underlying Go build diagnostic matters. ## Locked mode fails The operation would need to change `wago.json` or `wago-lock.json`. Preview it outside the final build: ```sh wago plugin update --dry-run --json ``` Review and commit the result, then retry locked mode. Locked mode can also fail when a transitive edge, source checksum, release fingerprint, provider catalog, definition digest, Authority Grant, configuration, or Contract binding no longer matches the committed graph. The locked rebuild identifies the exact field; do not hand-edit a digest or binding to silence it. ## Dependency resolution fails The plan reports every constraint and the parent that contributed it. If no global solution exists, update or remove the conflicting direct requirement rather than forcing one transitive version. Wago backtracks across available releases and prefers the highest deterministic complete solution, so a conflict means the published ranges genuinely cannot be satisfied together. A dependency or Contract cycle is invalid even when every individual range is compatible. Break the package edge or move the shared behavior behind a lower level Contract provider. ## Contract binding fails Check the consumer's Contract ID, major, and mode against the selected provider: ```sh wago plugin list --json ``` Required and optional Contracts accept at most one provider; `many` accepts the complete deterministic provider list. A different major is deliberately incompatible. Locked mode never silently chooses a replacement provider. ## An Authority is denied Inspect the published request and current grant: ```sh wago plugin inspect github.com/wago-org/workers wago plugin grant github.com/wago-org/workers ``` A required Authority must remain present, but its scope can be narrowed. If the plugin needs a withheld module or a larger minimum resource budget, registration fails before commit and your previous runtime stays active. A grant cannot widen the publisher's request. ## Offline mode fails A required module or artifact is missing locally. Fetch it during an intentional networked preparation step, then run the final build offline. ## Standalone compilation fails Preview the plan: ```sh wago compile fib.wasm --invoke fib --dry-run --json ``` Check that: - `_start` exists or `--invoke` names a real export; - the target is Darwin, Linux, or Windows on AMD64 or ARM64; - required plugins are selected; - every required Contract has its locked provider; - dependencies exist locally when offline mode is enabled; - plugins support the target. Show the Go build output: ```sh wago compile fib.wasm --invoke fib --verbose -o fib ``` --- Source page: https://docs.wago.sh/beta/using-plugins Markdown: https://docs.wago.sh/raw/beta/using-plugins.md # Using plugins Wago keeps host capabilities outside the core runtime. Plugins add the capabilities a module needs without putting every integration into Wago itself. In this guide, you will add WASI Preview 1 support to a local project and run a module that writes to standard output. ![Installing the WASI plugin and running a WASI module](/demos/wasi.gif) ## Before you begin You need: - Wago installed with a runtime selected. Complete [Getting started](./getting-started) first if `wago --version` does not show an active runtime. - [Go 1.22 or newer](https://go.dev/doc/install). Wago plugins are Go modules compiled into your runtime. Check both tools from your terminal: ```sh wago --version go version ``` ## Create a local Wago project Create or enter a directory for the example, then initialize it: ```sh mkdir wasi-example cd wasi-example wago init --run ``` This creates a `wago.json` manifest. Keeping the plugin local makes the project's dependencies and reviewed access reproducible instead of changing the runtime used by every project on your machine. ## Add WASI [WASI](https://wasi.dev/) defines system-style interfaces that WebAssembly modules can import. Wago provides those interfaces through the official [wago-org/wasi](https://plugins.wago.sh/wago-org/wasi) plugin: ```sh wago add wago-org/wasi ``` Keep **Preview 1** selected for this example. Review the source, dependencies, and requested Authorities before accepting them. Plugins are native Go dependencies; grants control access to privileged Wago integration APIs, but they do not sandbox arbitrary plugin code. Now, check to make sure it is installed: ```sh wago plugins list ``` > A lot of the subcommands have aliases so that it reads naturally. For example, `wago plugin` and `wago plugins` both work the same way. The command updates `wago.json`, writes the complete resolved graph and reviewed grants to `wago-lock.json`, and builds a project runtime. Commit both JSON files with your project. ## Download a WASI module This small module imports WASI Preview 1's `fd_write` function and calls it from `_start`: ```sh curl -fsSL https://wago.sh/corpora/wasi-hello.wasm -o wasi-hello.wasm ``` You can see the import before executing the module: ```sh wago module imports wasi-hello.wasm ``` ## Run it ```sh wago run wasi-hello.wasm ``` You should see: ```text hello from wasi ``` You can even compile it to a standalone executable: ::: code-group ```bash [macOS / Linux] wago compile wasi-hello.wasm -o wasi-hello ./wasi-hello ``` ```powershell [Windows] wago compile wasi-hello.wasm -o wasi-hello.exe .\wasi-hello.exe ``` > **Wago — finds the nearest `wago.json`, selects its project runtime, and uses the WASI plugin to satisfy the module's import.:** ## Where to go next ### [Install and choose scope](./guides/plugins/install-and-scope) Learn when to use local, global, or bare plugin selection. ### [Review grants and lockfiles](./guides/plugins/grants-and-lockfiles) Understand Authorities, guest capabilities, dependency graphs, and reproducible builds. ### [Write your own plugin](./guides/plugins/authoring/first-plugin) Scaffold a Go module and add a host import from definition to catalog. ### [Browse plugins](https://plugins.wago.sh) Find published host capabilities and runtime extensions. ### [Troubleshoot a build](./troubleshooting/plugins-and-builds) Fix missing Go tools, denied grants, stale lockfiles, and plugin build failures. --- Source page: https://docs.wago.sh/components Markdown: https://docs.wago.sh/raw/components.md # Documentation components Reusable components for clear, interactive Wago documentation. All components support keyboard navigation and narrow screens. ## Tabbed code examples Use VitePress's built-in code groups for examples in multiple languages or formats. ::: code-group ```go [Go] engine := wago.NewEngine() module, err := engine.Compile(wasm) if err != nil { return err } ``` ```wat [WAT] (module (func (export "answer") (result i32) i32.const 42)) ``` ```sh [CLI] wago run module.wasm ``` ## Tabbed sections ### Compile Compile a module once when it will be instantiated more than once. ```go module, err := engine.Compile(wasm) ``` ### Instantiate Create an isolated instance from the compiled module. ```go instance, err := module.Instantiate(ctx) ``` ### Run Call an exported WebAssembly function. ```go results, err := instance.InvokeValues(ctx, "answer") ``` Tabs with the same `sync` value remember the reader's choice and stay synchronized across the site. ## Cards ### [Get started](/canary/getting-started) Install Wago and run your first module. ### [Configuration](/canary/reference/configuration) Learn the available project settings. ### [Plugin registry](https://plugins.wago.sh/) Discover runtime extensions and integrations. ### [Source code](https://github.com/wago-org/wago) Read Wago's implementation on GitHub. ## Steps ### Install Wago ```sh curl -fsSL https://wago.sh/install.sh | sh ``` ### Compile a module Point Wago at a WebAssembly binary or WAT source file. ### Run it Execute the module and inspect its result. ## Status badges stable experimental deprecated beta ## Accordions ### What is compiled once? The validated module and native machine code can be reused by multiple isolated instances. ### Does Wago require cgo? No. Wago is implemented in pure Go. ## API endpoints ### GET /api/packages List published plugins. ### POST /api/packages/{name}/installs Record a completed plugin installation. ## Comparisons ## File trees - `.vitepress/` - `config.mts` - `theme/` - `getting-started.md` - `reference/` ## Code annotations ```wat (module (func (export "answer") (result i32) i32.const 42)) ``` The `answer` export is available to the host by name. The function returns one 32-bit integer. `i32.const` places the value `42` on the operand stack. --- Source page: https://docs.wago.sh/canary/getting-started Markdown: https://docs.wago.sh/raw/canary/getting-started.md # Getting started This guide takes you from an empty machine to a successful WebAssembly call. You will install the Wago version manager, select a runtime, download a tiny module, and run it. ## Before you begin Use a supported macOS, Linux, or Windows machine with network access and a writable home directory. The shell examples below use `curl` on macOS/Linux or PowerShell on Windows. Install [Go 1.22 or newer](https://go.dev/dl/) and [Git](https://git-scm.com/downloads) before starting if you use the Go installer or need a source-build fallback. Released binaries do not always exist for the selected channel and platform. Go is also required for plugins and standalone executables; a downloaded prebuilt core runtime can run without it. ## Install the manager ::: code-group ```bash [Go Install] go run github.com/wago-org/wago/cli/wago-installer@latest ``` ```bash [macOS / Linux] curl -fsSL https://install.wago.sh/unix | sh ``` ```powershell [PowerShell] irm https://install.wago.sh/ps | iex ``` > **The — installer prints where it put `wago`. If it updated your `PATH`, open a new terminal. If it instead asks you to add the default `~/.wago/bin` directory yourself, add it for the current shell::** ::: code-group ```sh [macOS / Linux] export PATH="$HOME/.wago/bin:$PATH" ``` ```powershell [PowerShell] $env:Path = "$HOME\.wago\bin;$env:Path" ``` > **Use — the actual directory printed by the installer if you chose another location. Add the same directory to your shell's startup configuration or Windows user `Path` to keep it for future terminals. Then check that your shell can find it::** ```sh wago --version ``` You can think of the wago command as a **version manager**. It handles version installing, upgrading, and switching. In order to run wasm, you need to install the actual runtime. If you only need Wago as a library in an existing Go project, add the package directly: ```sh go get github.com/wago-org/wago ``` ## Install a runtime ```sh wago version install ``` The interactive picker lets you choose a channel and build. For a repeatable first run without prompts, install the current beta's standard Go build: ```sh wago version install --beta --profile standard --build normal --use --no-input wago --version ``` The first core-module example below works with the beta runtime. These are the **canary development docs**; use the version selector for documentation matching a released runtime. The selector changes the pages you read, not the runtime installed on your machine. [Configuration and versions](./guides/cli/configuration#pick-a-channel) shows how to switch to canary before trying development-only features. Go applications select their library version separately in `go.mod`; the embedding guides show that step explicitly. ## Download a small module ![Downloading, inspecting, and running the Fibonacci module](/demos/run-module.gif) ```sh curl -fsSL https://wago.sh/corpora/fib.wasm -o fib.wasm ``` This module exports a function named `fib`. It takes one `i32` argument and returns the corresponding Fibonacci number. You can inspect its exports before running it: ```sh wago module exports fib.wasm ``` The module exports a `fib (i32) -> i32` function. Without `--invoke`, Wago selects `_start`, then `main`, then the module's only exported function—in this case, `fib`. If several exported functions remain, name one with `--invoke` or `-e`. ## Run it In this case, `fib` is the only exported function, so Wago selects it automatically: ```sh wago fib.wasm 30 ``` You should see: ```text 832040 ``` ## Try the everyday commands You need [Go 1.22 or newer](https://go.dev/) on `PATH` to build a standalone executable. TinyGo builds need **both Go and TinyGo**; the smaller build is an optional next step in [Standalone executables](./guides/cli/standalone). Create a standalone executable: ::: code-group ```bash [macOS / Linux] wago compile fib.wasm -o fib ./fib 30 ``` ```powershell [PowerShell] wago compile fib.wasm -o fib.exe .\fib.exe 30 ``` ```cmd [Command Prompt] wago compile fib.wasm -o fib.exe fib.exe 30 ``` > **The — output includes its runtime. You can copy it to another machine with the:** same operating system, architecture, and compatible CPU features and run it without installing Wago. Keep the original `.wasm` when you need to rebuild for a different target. ## Where to go next ### [Use the CLI well](./guides/cli) Pick exports, pass typed arguments, watch files, inspect imports, and precompile modules. ### [Embed Wago in Go](./guides/embed/runtime-and-modules) Move from a shell command to a long-lived runtime inside your application. ### [Add host capabilities](./using-plugins) Install the WASI plugin, review its requested access, and run a module that uses it. ### [Fix a first-run problem](./troubleshooting) Diagnose PATH, runtime selection, imports, exports, and stale precompiled files. --- Source page: https://docs.wago.sh/canary/guides/cli Markdown: https://docs.wago.sh/raw/canary/guides/cli.md # Use the CLI Start with [installation and your first module](../getting-started). These guides cover the next steps: - [Run and inspect modules](./cli/running-modules): choose exports, pass arguments, inspect metadata, watch files, and reuse compiled code - [Build a standalone executable](./cli/standalone): package a module with Go or TinyGo so it runs without an installed Wago command - [Profile and debug a workload](./cli/profiling): reproduce traps, collect a checked workload, and read timing or CPU reports - [Configure Wago](./cli/configuration): keep project settings and compiler options consistent ## Find the right command ```sh wago run --help wago module --help wago build --help wago compile --help wago run --help-optimizations ``` `run` executes Wasm. `build` saves a host-specific `.wago` artifact for later use by Wago. `compile` produces a standalone executable containing the runtime and precompiled guest code. For machine-readable inspection, add `--json` to `validate`, `module imports`, `module exports`, or `module capabilities`. The available flags depend on the selected runtime's platform and build profile; use its help output when a flag is missing. --- Source page: https://docs.wago.sh/canary/guides/cli/configuration Markdown: https://docs.wago.sh/raw/canary/guides/cli/configuration.md # Configure and manage Wago The `wago` command is a manager. The runtime it selects does the actual Wasm work. Updating one does not automatically mean you changed the other. There are three separate choices: the manager executable on `PATH`, the selected CLI runtime, and the Wago library version in each Go application's `go.mod`. A `go get` does not switch the CLI runtime. The documentation version selector changes none of them. ## Know what is running ```sh wago --version wago version current wago version which wago status ``` `--version` shows the runtime release, platform, toolchain, and manager. `version current` shows the selected channel or version plus its profile and build; a channel name alone is not an exact revision. `version which` prints the executable path. `status` also shows the project and plugin lockfile. Copy `wago --version` output when reporting a bug. ## Pick a channel Install the latest beta without prompts: ```sh wago version install --beta --profile standard --build normal --use --no-input ``` Or switch to a development build: ```sh wago version switch canary --profile standard --build normal ``` Switching installs a missing runtime. `beta` and `canary` move over time. Once a release or commit works for your project, use its exact tag or commit in scripts: ```sh wago version install --version --profile standard --build normal --use --no-input ``` Replace `` with the revision you tested. A commit build may need Git, Go, and network access; it is not a promise that a release asset exists. Go applications should pin their Wago dependency in `go.mod` too. ## Choose a profile and build Start with `standard/normal` unless you have a reason to change it. | Choice | What it means | |---|---| | `--profile standard` | Full runtime command surface | | `--profile minimal` | Smaller, run-only runtime; do inspection and compilation with standard | | `--build normal` | Built with the standard Go compiler | | `--build tiny` | Built with TinyGo; availability depends on the version and target | For example: ```sh wago version install --beta --profile minimal --build normal --use --no-input ``` That example makes the run-only profile active. Switch back before continuing the inspection and standalone tutorials: ```sh wago version switch beta --profile standard --build normal ``` These switches choose the installed runtime. `wago compile --tinygo` separately chooses the linker for a [standalone executable](./standalone). ## Save defaults where they belong Inside a project: ```sh wago init --run --yes --no-input wago config set optimizations.inline off --local wago config diff --local wago config reset optimizations.inline --local ``` Reset removes the local override and restores inheritance. Use `--global` for user-wide settings; a command flag overrides both. See [Configuration](../../reference/configuration) for the complete precedence and manifest format. ## Update deliberately Preview a coordinated manager, runtime, and plugin update before applying it: ```sh wago update --all --dry-run --json wago update --all ``` Run your module's smoke test after updating. Keep the Wasm source for any precompiled `.wago` files so you can rebuild them when the artifact format changes. Commit project manifests and plugin lockfiles together. ## Add shell completion ```sh wago config completions zsh --install --dry-run wago config completions zsh --install ``` Replace `zsh` with `bash` or `fish`. The preview shows the planned change before you modify shell startup files. --- Source page: https://docs.wago.sh/canary/guides/cli/profiling Markdown: https://docs.wago.sh/raw/canary/guides/cli/profiling.md # Profile and debug a workload Start with a reproducible call and an expected result. A profile of the wrong computation is not useful, even if it looks faster. ## Reproduce a trap First check the input and the export signature: ```sh wago validate module.wasm wago module imports module.wasm wago module exports module.wasm wago run --invoke process module.wasm 42 ``` Replace the filename, export, and arguments with the failing call. Run outside watch mode so one invocation produces one error. For a small example, save this as `trap.wat`: ```wat (module (func (export "trap") unreachable)) ``` With [WABT's `wat2wasm`](https://github.com/WebAssembly/wabt) installed: ```sh wat2wasm trap.wat -o trap.wasm wago validate trap.wasm wago run --invoke trap trap.wasm ``` Validation succeeds, but the call fails: ```text wago: trap: unreachable instruction executed at trap (func[0], wasm pc 0x1) ``` Keep the original module, arguments, Wago version, and compiler settings when reporting a trap. A Wasm frame identifies an export/function and Wasm instruction position; it is not automatically a guest-language source line. In an embedded application, `context.Canceled` and `context.DeadlineExceeded` indicate host cancellation, so handle them separately from guest traps. ## Build the optional profiler Ordinary Wago builds do not include `wago profile`. From a [Wago source checkout](https://github.com/wago-org/wago), with Go installed, build the profiling CLI: ```sh git clone https://github.com/wago-org/wago.git cd wago ./scripts/build-profiler.sh ./wago-profile --cli ./wago-profile profile --help ``` The examples below use this separate `wago-profile` binary. It profiles the engine built into that binary. Switching your installed Wago runtime does not change it, and it does not resolve your project's plugins. Keep the checkout revision with your results; the build script records it in each capture. The profiler is experimental. Check the [profiling qualification record](https://github.com/wago-org/wago/blob/main/docs/profiling-qualification.md) before relying on a particular collector or target. ## Record a checked workload This first capture needs no external sampler: ```sh curl -fsSL https://wago.sh/corpora/fib.wasm -o fib.wasm ./wago-profile profile record \ --module fib.wasm --export fib --args 20 --want 6765 \ --iterations 1000 --warmup 5 --source-maps --timeline \ --out fib.wagoprof ./wago-profile profile top fib.wagoprof ``` Each iteration must return `6765`. A wrong result fails the capture rather than becoming a successful timing. `fib.wagoprof` is a directory; choose a new output path for every run. Existing captures are never replaced. The default backend is `none`. It records elapsed phase timings, completed work, and static compiler data. `top` explicitly reports that no native samples are available. Compiler code size, frame size, or emitted checks are not measured hotspots. Unlike `wago run`, profiler arguments and expected results are comma-separated unsigned 64-bit ABI slots. Floating-point values use their bit representation; vectors take two slots. Use `--want '[]'` for a void result, and `--init NAME` for an initialization export. The built-in import environment only supplies a trapping `env.abort`; arbitrary imports and WASI commands need a custom host using the [profiling library](https://github.com/wago-org/wago/blob/main/docs/profiling.md). ## Read the capture ```sh ./wago-profile profile annotate fib.wagoprof --function fib --json ./wago-profile profile timeline fib.wagoprof ./wago-profile profile top fib.wagoprof --json ``` - `top` summarizes measured samples when present, plus compiler statistics - `annotate` joins captured function metadata and available instruction samples; `--source-maps` retains Wasm lowering origins and static inline ancestry - `timeline` shows recorded invocation and host-boundary spans when the capture used `--timeline`. These are elapsed boundaries, not CPU time Start with `manifest.json` when a capture looks incomplete. It records the module and workload hashes, revision, target, backend, invocation mode, effective settings, requested and completed work, diagnostics, and completion status. Keep the whole directory together when sharing or moving it. ## Collect native CPU samples on Linux Install a working Linux `perf` tool and use an environment whose existing permissions allow performance events. This path also needs permission to write the capture directory: ```sh ./wago-profile profile record \ --backend perf --include-code --source-maps \ --module fib.wasm --export fib --args 20 --want 6765 \ --phase execute --duration 15s --rate 99 \ --out fib-perf.wagoprof ./wago-profile profile top fib-perf.wagoprof ./wago-profile profile annotate fib-perf.wagoprof --function fib --assembly perf report -i fib-perf.wagoprof/perf.jit.data go tool pprof -top fib-perf.wagoprof/native.pprof ``` `--include-code` retains native machine-code bytes and is required for this backend. Native collection was not available in the isolated walkthrough environment because `perf` was absent; the commands above follow the implementation and the linked qualification record. A missing collector or permission error is a failed capture, not evidence of zero CPU cost. Do not change host security settings just to make a capture succeed; use an appropriately configured development machine. For a Go process CPU profile without an external collector: ```sh ./wago-profile profile record \ --backend pprof --module fib.wasm --export fib --args 20 --want 6765 \ --phase execute --duration 1s --out fib-go-cpu.wagoprof go tool pprof -top fib-go-cpu.wagoprof/cpu.pprof ``` This reports Go process activity, including the invocation harness. It does not promise native guest attribution. For host-heavy work, select `--phase compile` or `--phase reload`; very short phases may produce no samples. On macOS, `--backend samply` requires an installed Samply collector and observes all process phases; do not interpret it as isolated execute-only CPU time. ## Compare equivalent work Record a second capture using the same module, expected result, phase, backend, invocation mode, and collection settings. Then compare the directories: ```sh ./wago-profile profile diff baseline.wagoprof candidate.wagoprof ``` Use actual capture paths. The report normalizes by completed work and rejects incompatible measurement contracts. With the `none` backend, the comparison is elapsed time per iteration. A single pair does not establish a repeatable improvement; collect multiple runs under comparable conditions. `--mode public` includes named `Instance.Invoke` lookup. `--mode prepared` uses a resolved function. Both include result validation, and changing the mode changes what you measure. ## Bound the recording and protect its contents Choose `--iterations N` or `--duration D`. Duration is checked between complete iterations, so a long guest call can overshoot it. A separate `--collection-timeout` supervises the whole process, including a guest call that never returns; it defaults to five minutes. `--conversion-timeout` bounds native conversion and defaults to two minutes. Expiry leaves an incomplete capture and diagnostics. Raw stack capture is a separate experimental opt-in, not enabled by `--source-maps` or `--timeline`. On supported Linux/amd64 perf setups, `--stack-bytes` requires `--unwind-maps` and `--include-code`. Raw stack memory may contain sensitive data. Leave it off unless you need it, and review capture contents before sharing. See the [full profiling reference](https://github.com/wago-org/wago/blob/main/docs/profiling.md) for collection limits and qualified stack recovery. --- Source page: https://docs.wago.sh/canary/guides/cli/running-modules Markdown: https://docs.wago.sh/raw/canary/guides/cli/running-modules.md # Run and inspect modules You need an [installed Wago runtime](../../getting-started). Download the small Fibonacci module used below: ```sh curl -fsSL https://wago.sh/corpora/fib.wasm -o fib.wasm ``` ## Check the module first ```sh wago validate fib.wasm wago module exports fib.wasm wago module imports fib.wasm wago module capabilities fib.wasm ``` The exports include: ```text exports: fib func (i32) -> i32 memory memory min=0 ``` `imports` shows each import and whether the selected runtime's plugins provide it. `capabilities` lists the capabilities associated with imports. These reports help identify missing host support; they do not grant access. See [using plugins](../../using-plugins) for that step. `validate` checks the Wasm binary without running it. The inspection commands compile it to obtain metadata, but do not instantiate it or call its exports. Successful validation alone does not prove that the current runtime has every required feature or host import. All four commands accept JSON output: ```sh wago validate --json fib.wasm wago module exports --json fib.wasm wago module imports --json fib.wasm wago module capabilities --json fib.wasm ``` Exports report functions, globals, tables, memories, and exception tags, with the fields relevant to each kind. Memory and table limits are Wasm limits; memory sizes are in pages. ## Call an export ```sh wago run --invoke fib fib.wasm 30 ``` ```text 832040 ``` `-e` is the short form of `--invoke`. If you omit it, Wago looks for `_start`, then `main`, then the sole exported function. Multiple remaining functions need an explicit choice. You can also omit `run`: ```sh wago fib.wasm 30 ``` Arguments use the function's declared parameter types. An explicit suffix controls how a value is encoded: ```sh wago run --invoke fib fib.wasm 20:i32 ``` The supported suffixes are `i32`, `i64`, `f32`, and `f64`. Match the declared type; a suffix is not a change to the Wasm signature. The CLI accepts numeric parameters and results. Use the [Go API](../embed/runtime-and-modules) for reference or `v128` values. Keep Wago flags before the module path for readability. Flags can also follow the path. If a guest command needs an option with the same name as a Wago flag, put `--` before the guest arguments: ```sh wago run command.wasm -- --help ``` This example assumes `command.wasm` is a command-style guest with `_start` and the required argument-supporting plugin. `fib.wasm` takes a function parameter instead. ## Call several exports on one instance Repeat `--invoke` to call functions in order. Wago consumes arguments according to each function's arity: ```sh wago run --invoke fib --invoke fib fib.wasm 20 30 ``` ```text 6765 832040 ``` The calls share one instance, including its memory and globals. This is useful for an initialization export followed by a worker export. Values left over after the selected functions' parameters are not passed as extra function parameters. ## Rerun after a rebuild On Linux and Windows, the standard runtime can watch a Wasm file: ```sh wago run --watch --watch-interval 200ms --invoke fib fib.wasm 20 ``` Rebuild the `.wasm` file in another terminal. Wago reruns when its contents change; it does not compile your guest-language source. Press Ctrl+C to stop. Watch flags are currently absent on macOS and lean builds. On Linux, launch through the `wago` manager; its process supervisor also needs procfs child lists. A restricted container that hides those lists cannot use watch mode. ## Adjust compilation and stack capacity Use adaptive parallel validation and compilation for a large module, or set a worker maximum: ```sh wago run -p --invoke fib fib.wasm 20 wago run --parallel=4 --invoke fib fib.wasm 20 ``` Small modules may be slower with extra workers. Compare your actual workload before keeping the setting. If a deeply recursive guest exhausts its native execution stack, increase its capacity: ```sh wago run --native-stack 8MiB --invoke fib fib.wasm 20 ``` The default is 4 MiB. Accepted capacities range from 512 KiB to 1 GiB and must be 16-byte aligned. The suffixes `B`, `KiB`, `MiB`, and `GiB` are case-sensitive. This controls the execution stack, not the guest's linear memory or WasmGC heap. `--core 2` requests the strict Core 2 feature set; `--core 3` requests the complete Core 3 set on a supported target. The default chooses the best supported feature set. [Configuration](./configuration) covers compiler settings and their precedence. ## Save compiled code for later ```sh wago build fib.wasm -o fib.wago wago run --allow-native-artifact --invoke fib fib.wago 20 ``` ```text 6765 ``` A `.wago` artifact contains native code. Enable `--allow-native-artifact` only for files you built or otherwise trust. It is an explicit trust decision, not a validator for downloaded machine code. Keep the original `.wasm`: the CLI's validation and module-inspection commands read Wasm, not `.wago` artifacts. Rebuild artifacts for each target platform, after incompatible Wago upgrades, and when the compiler or plugin configuration changes. For a distributable program that does not need Wago installed, [build a standalone executable](./standalone). --- Source page: https://docs.wago.sh/canary/guides/cli/standalone Markdown: https://docs.wago.sh/raw/canary/guides/cli/standalone.md # Build a standalone executable `wago compile` packages precompiled guest machine code, a runtime, and the selected plugins into one executable. The recipient can run it without an installed `wago` command, Go toolchain, or separate `.wasm` file. ## Before you start - Install the [Wago manager](../../getting-started) - Install [Go 1.22 or newer](https://go.dev/dl/) and put `go` on `PATH` - Keep the module's plugin configuration in the project where you build The first build may download Go modules, so it can take longer and need network access. If Wago cannot locate its source for a development build, set `WAGO_SRC` to the matching Wago checkout. Normal installations retain the source they need. ## Build with Go ![Building and running a standalone Fibonacci executable](/demos/standalone.gif) This example needs no host imports or plugins: ```sh curl -fsSL https://wago.sh/corpora/fib.wasm -o fib.wasm go version wago compile --bare --invoke fib fib.wasm -o fib ./fib 30 ``` ```text 832040 ``` On Windows, use `-o fib.exe` and run `.\fib.exe 30` in PowerShell. If you omit `-o`, Wago removes the input's extension and adds `.exe` on Windows. The module is compiled before the executable is linked. At startup, the executable loads that embedded artifact rather than invoking Wago's Wasm compiler again. ## Build a smaller executable with TinyGo Install [TinyGo](https://tinygo.org/getting-started/install/) as well as Go. Both commands must be on `PATH`: Wago uses Go to prepare the native artifact and TinyGo for the final link. Linux also needs `strip`, usually supplied by binutils; macOS supplies it with the command-line developer tools. The tested baseline for this walkthrough is TinyGo 0.41.1 with Go 1.25.0 on Linux/amd64: ```sh go version tinygo version wago compile --bare --tinygo --invoke fib fib.wasm -o fib-tiny ./fib-tiny 30 ``` ```text 832040 ``` Use a Go version supported by your TinyGo release. Wago builds with TinyGo's task scheduler, conservative collector, and size optimization, then strips the result. Test the actual module and plugin set you intend to ship; their Go dependencies must also work with TinyGo. > **Warning — TinyGo 0.42.0:** The Linux/amd64 walkthrough also tested TinyGo 0.42.0 with Go 1.25.0. Its final link fails with a duplicate `tinygo_task_exit` symbol in the task-scheduler runtime. A small Go channel/goroutine program reproduces the same failure without Wago. Use the tested 0.41.1 combination for this path until that toolchain issue is resolved. ## Choose the entry point and arguments `--invoke` fixes the export the executable will call. Without it, selection follows `_start`, then `main`, then the sole exported function. For a numeric export, arguments after the executable name become its parameters: ```sh ./fib 20:i32 ``` ```text 6765 ``` For a command-style guest, `_start` receives no function parameters. The executable's argument list is available to the configured guest argument provider, such as WASI. Numeric calls use the [same supported value types](./running-modules#call-an-export) as `wago run`. The resulting program does not expose the Wago CLI. Pass compilation options to `wago compile`, rather than to the executable: ```sh wago compile --bare --core 2 --parallel=4 --invoke fib fib.wasm -o fib ``` Core features, compiler options, and plugin configuration are fixed during the build. `wago compile --help-optimizations` lists the advanced controls. Native-stack and WasmGC heap flags belong to `wago run`; they are not standalone compile flags. ## Include the plugins your guest needs Build from the configured project directory. A project manifest takes precedence; without one, Wago uses the shared user-wide selection. You can choose the scope explicitly: ```sh wago compile --local command.wasm -o command wago compile --global command.wasm -o command ``` These commands assume `command.wasm` and its plugins are already configured. Use `--bare` only when the module needs no plugin imports. Review [plugin setup and permissions](../../using-plugins) before packaging a guest that reads files or uses other host capabilities. The selected providers and their configuration are embedded in the executable. External files named by that configuration are not automatically copied into it. Check paths and permissions on the destination machine, and rebuild when plugin code or configuration changes. ## Build on the destination platform The machine code is generated for the build host. `--target` must match that host; it does not enable cross-compilation. For example, a Linux/amd64 host rejects: ```sh wago compile --target darwin/arm64 fib.wasm -o fib-mac ``` ```text precompiled standalone builds require the native target linux/amd64; got darwin/arm64 ``` Use a native build machine or CI runner for each platform. TinyGo standalone support is limited to Linux/amd64, Linux/arm64, and macOS/arm64. The Go path also supports Wago's other native targets; feature availability still depends on the selected platform. ## Diagnose a failed build ```sh wago compile --bare --verbose --invoke fib fib.wasm -o fib ``` `--verbose` shows the underlying build output. Check the first error: - Missing `go`, `tinygo`, or `strip`: install the required tool and check `PATH` - Unsupported Go version in TinyGo: select a compatible Go toolchain - Module download failure: check network access and writable Go caches - Missing import: build with the plugin configuration required by the guest - Native-target error: build on the matching OS and architecture Keep the original Wasm and record your Wago, Go, TinyGo, and plugin versions alongside release builds. Rebuild when the runtime or plugin configuration changes. --- Source page: https://docs.wago.sh/canary/guides/components Markdown: https://docs.wago.sh/raw/canary/guides/components.md # Run a WebAssembly component A component can connect core Wasm modules behind typed interfaces. Wago's optional [Component Model plugin](https://github.com/wago-org/component-model) handles that graph and the Canonical ABI. The [WASI plugin](https://github.com/wago-org/wasi) supplies Preview 2 command policy and host interfaces. This guide runs a small component from Go, then uses the same service to run a Preview 2 command. You need Go 1.22 or newer on a supported Wago host. > **Info — Choose the execution path:** The current `wago run` command accepts core Wasm modules. Adding the Component Model or WASI `/p2` provider does not make it a component-command runner. Passing a component binary to it reports `bad version at offset 4`. Use the typed Go service below for components. Use [WASI Preview 1](./wasi) when you need the existing CLI command path. ## Run the complete example The [walkthrough fixture](https://github.com/wago-org/docs/tree/c10fc427b008e71878e9cb890e2c609d0f008a8c/demos/fixtures/plugins-walkthrough/components) includes the complete host, explicit provider selections, and pinned Go dependencies. Clone the docs, select the tested fixture revision, and enter its directory: ```sh git clone https://github.com/wago-org/docs.git cd docs git checkout c10fc427b008e71878e9cb890e2c609d0f008a8c cd demos/fixtures/plugins-walkthrough/components go mod download ``` Download the Component Model repository's small adder fixture: ```sh curl -fsSL https://raw.githubusercontent.com/wago-org/component-model/d96ac8770288d303ebdfc8b84732ba553236aea4/testdata/adder.wasm -o adder.wasm go run . add adder.wasm ``` Expected output: ```text add(2, 3) = 5 ``` The guest is already compiled. You do not need Rust, `wasm-tools`, or another guest compiler to run it. ## Declare the service you need The host acts as a small consumer plugin. Its definition has both a package dependency and a typed Contract requirement: ```go Requires: []wago.PluginRequirement{{ ID: component.PluginID, Version: "^0.1.0", }}, Consumes: []wago.ContractRequirement{{ ID: component.Contract.ID(), Major: component.Contract.Major(), Mode: wago.ContractRequired, }}, ``` The package selects an implementation. The Contract identifies its typed service. The reviewed `PluginSet` must select both providers, mark the consumer as a direct root, and bind that exact Contract to the Component Model provider. The fixture shows all three pieces; a definition alone does not activate the graph. During registration, obtain the reference: ```go func (p *consumer) Register(reg *wago.Registrar) error { var err error p.components, err = plugin.Require(reg, component.Contract) return err } ``` Here, `p.components` has type `*plugin.Ref[component.Service]`. ## Call a typed export Use the service inside its lease, then use the component instance inside its own callback: ```go err := host.components.With(func(service component.Service) error { return service.WithInstance(ctx, wasm, func(in *component.Instance) error { values, err := in.CallExport( ctx, "component:adder/calc", "add", uint32(2), uint32(3), ) if err != nil { return err } fmt.Println(values[0]) return nil }) }) ``` The interface, function, and value types must match the component's exports. This adder takes two WIT `u32` values, so the Go arguments are `uint32`. `WithInstance` closes the complete component graph before returning. Do not retain the instance outside that callback. Do not retain the service outside `Ref.With`. Close component callbacks and caches before closing the Wago runtime. ## Run a Preview 2 command The same fixture has a `wasi` mode. Download the WASI repository's compiled Rust smoke command: ```sh curl -fsSL https://raw.githubusercontent.com/wago-org/wasi/397f6e142b4d2d3fca0a59b9f3f56c9326478041/p2/testdata/rust_smoke.component.wasm -o command.component.wasm printf 'from-component-stdin\n' | go run . wasi command.component.wasm alpha beta ``` The command prints its arguments, the explicitly supplied environment value, its stdin, and checks for a working clock and random-seeded map. It also writes `rust-wasip2-stderr` to stderr. Inside the fixture, this path calls `p2.Run` with the leased Component Model service: ```go return p2.Run(ctx, service, wasm, p2.Config{ Stdin: p2.NewInputStream(os.Stdin), Stdout: p2.NewOutputStream(os.Stdout), Stderr: p2.NewOutputStream(os.Stderr), Args: []string{"command.component.wasm", "alpha", "beta"}, Env: []string{"WAGO_FLAVOR=docs"}, }) ``` `Args` is the complete argument vector, including `argv[0]`. Ordinary Go readers and writers need `NewInputStream` and `NewOutputStream` adapters. The runner locates the versioned `wasi:cli/run` export and closes its adapter graph on return. For a plugin whose configuration should come from Wago's reviewed lock graph, select `github.com/wago-org/wasi/p2` and consume `p2.Contract` instead. Its `p2.Service.Run(ctx, wasm)` uses the provider's selected configuration. That path also requires the Component Model dependency and both exact Contract bindings. Preview 2 starts with an empty environment and no filesystem mounts. Its socket and name-lookup imports return typed `access-denied` results while networking is disabled. Use explicit `Mounts` when a command needs files. The [WASI guide](./wasi#grant-a-directory) explains the rights model. ## Review resource limits The Component Model provider requests three required Authorities: - `core.module.compile` to compile embedded core modules; - `core.instance.instantiate` to own their bounded instance graph; and - `core.funcref.create` to link Canonical ABI bridges. Review the positive instance and aggregate memory limits shown for the exact selected release. A component may contain several core modules, and memoryless shims still use instance slots. Memory accounting uses declared maximum memory, or Wago's implementation reservation when a module declares no maximum. The charged budget can exceed the guest's currently used memory. If a component exceeds the reviewed limit, it fails. Inspect its graph and choose an appropriate bounded grant; do not grant arbitrary limits as a first debugging step. These Authorities govern Wago APIs, while the plugin itself remains trusted native Go code. ## Add your own host interface Use `component.WithImport` for a synchronous typed host function. This example returns its string argument: ```go stringType := component.PrimitiveDesc{Prim: "string"} echo := component.WithImport( "example:host/echo@1.0.0", "echo", func(ctx context.Context, args []component.Value) ([]component.Value, error) { return []component.Value{args[0]}, nil }, []component.TypeDesc{stringType}, []component.TypeDesc{stringType}, ) ``` Pass `echo` after the callback to `service.WithInstance(ctx, wasm, useInstance, echo)`. Match the component's imported interface version and function signature exactly. For composite types, resources, caches, and experimental async APIs, continue with the [provider's public API and tests](https://github.com/wago-org/component-model). For the underlying dependency lifecycle, read [Contracts and dependencies](./plugins/authoring/contracts). --- Source page: https://docs.wago.sh/canary/guides/embed/artifacts Markdown: https://docs.wago.sh/raw/canary/guides/embed/artifacts.md # Cache compiled code A `.wago` artifact stores host-native compiled code. It removes compilation from startup, but it is specific to Wago's artifact format, the target operating system, architecture, and required CPU features. Use the `module.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "slices" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("module.wasm") if err != nil { return err } compiled, err := wago.Compile(nil, wasm) if err != nil { return err } artifact, err := compiled.MarshalBinary() closeErr := compiled.Close() if err != nil { return err } if closeErr != nil { return closeErr } if err := os.WriteFile("module.wago", artifact, 0o600); err != nil { return err } trustedBytes, err := os.ReadFile("module.wago") if err != nil { return err } trusted, err := wago.LoadTrustedArtifact(trustedBytes) if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.AdoptModule(trusted) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer instance.Close() if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeContext(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeContext(ctx, "add", wago.I32(20), wago.I32(22)) if err != nil { return err } fmt.Printf("artifact: %d bytes\n", len(artifact)) fmt.Println(wago.AsI32(results[0])) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` The artifact size varies by Wago version and architecture. The final line remains: ```text 42 ``` ## Treat artifacts as executable code `LoadTrustedArtifact` is intentionally explicit: a `.wago` file contains native machine code. Load only bytes produced locally or authenticated by your application. Use normal `Runtime.Compile` for untrusted `.wasm` input. Keep the original Wasm. Rebuild artifacts after an incompatible Wago update and for every operating-system and architecture target you ship. If plugins or custom compiler extensions affect compilation, build and load the artifact through the same runtime configuration and plugin generation. An artifact contains compiled module code and metadata, not a running instance's memory, globals, or tables. Loading it and instantiating it starts the guest from its initial state. Imports still need to be bound, and a reactor's `_initialize` export still needs to run once per new instance. `Load` accepts raw Wasm and refuses native `.wago` artifacts; `LoadTrustedArtifact` accepts only artifacts. If an artifact is incompatible, recompile the original `.wasm` with the target runtime instead of bypassing its format or CPU checks. Keep trusted artifacts in an application-owned location and verify their provenance before loading them. In this example, `AdoptModule` transfers the loaded artifact's ownership to the returned module, and closes it if adoption fails. Closing that module releases the compiled artifact when its users have finished. `Runtime.Module` is the non-owning alternative, so its caller must keep and close the original compiled object. --- Source page: https://docs.wago.sh/canary/guides/embed/calls-and-state Markdown: https://docs.wago.sh/raw/canary/guides/embed/calls-and-state.md # Work with calls and state Continue in the project from [Run WebAssembly from Go](./runtime-and-modules). The short call snippets below fit inside that program; the counter example later on replaces `main.go`. Its guest needs WABT's `wat2wasm`, even if you used another language for the first guest. For normal calls, use `InvokeContext` when you have a request context, or `Invoke` when you do not need cancellation. Both use raw `uint64` ABI slots: | Wasm type | Encode an argument | Read a result | |---|---|---| | `i32` | `wago.I32(v)` | `wago.AsI32(slot)` | | `i64` | `wago.I64(v)` | `wago.AsI64(slot)` | | `f32` | `wago.F32(v)` | `wago.AsF32(slot)` | | `f64` | `wago.F64(v)` | `wago.AsF64(slot)` | Encode the type the export actually declares. Casting a Go float to `uint64` does not preserve its WebAssembly bit representation. If you also have the [Wago CLI installed](../../getting-started), inspect a module with `wago module exports module.wasm` when the signature is unclear. Raw results belong to the instance and remain valid only until its next invocation. Read or copy them before another call, including a call through a resolved `WasmFunc`: ```go out, err := instance.InvokeContext(ctx, "add", wago.I32(20), wago.I32(22)) if err != nil { return err } saved := append([]uint64(nil), out...) fmt.Println(wago.AsI32(saved[0])) ``` ## Choose typed checks when you need them `InvokeValues(ctx, name, args...)` remains available, but is deprecated in the current API in favor of `Invoke` and `InvokeContext`. It is useful when you specifically need type checking, independently owned result slices, or Runtime invocation hooks. The raw APIs do not run those typed invocation hooks. ```go out, err := instance.InvokeValues(ctx, "add", wago.ValueI32(20), wago.ValueI32(22)) if err != nil { return err } fmt.Println(out[0].I32()) ``` Use `ValueI64`, `ValueF32`, and `ValueF64` with the matching result accessor for the other scalar types. Supplying `ValueF64(20)` to an `i32` parameter is rejected before the guest executes. A `v128` is not a typed `Value`; the raw API uses two adjacent little-endian `uint64` slots for it. Non-null reference slots are store-owned tokens, not Go pointers or portable numeric IDs. ## See instance state survive Create `counter.wat`: ```wat (module (global $count (export "count") (mut i32) (i32.const 0)) (func (export "inc") (result i32) global.get $count i32.const 1 i32.add global.set $count global.get $count)) ``` Compile it with [WABT](https://github.com/WebAssembly/wabt): ```sh wat2wasm counter.wat -o counter.wasm ``` Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("counter.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer instance.Close() for range 3 { results, err := instance.InvokeContext(ctx, "inc") if err != nil { return err } fmt.Println(wago.AsI32(results[0])) } count, err := instance.GlobalValue("count") if err != nil { return err } fmt.Println("count:", count.I32()) if err := instance.SetGlobalValue("count", wago.ValueI32(40)); err != nil { return err } results, err := instance.InvokeContext(ctx, "inc") if err != nil { return err } fmt.Println("after set:", wago.AsI32(results[0])) fresh, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer fresh.Close() results, err = fresh.InvokeContext(ctx, "inc") if err != nil { return err } fmt.Println("fresh instance:", wago.AsI32(results[0])) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 1 2 3 count: 3 after set: 41 fresh instance: 1 ``` One instance preserves state and serializes calls. This includes mutations made before a trap or cancellation: errors do not roll state back. A fresh instance starts with the module's initial state while reusing the same compiled code. ## Resolve a frequently used export A `WasmFunc` resolves an export once. It still checks the instance lifecycle on every invocation, accepts arbitrary supported arity, and returns the same kind of borrowed result slice as `Invoke`: ```go inc, err := instance.WasmFunc("inc") if err != nil { return err } out, err := inc.Invoke() if err != nil { return err } fmt.Println(wago.AsI32(out[0])) ``` This handle does not reserve the instance between calls. Use `InvokeContext` when each call needs a context, and close the instance when its state is no longer needed. After close, both named and resolved calls fail. ## Add guest memory [Exchange bytes with a guest](./guest-memory) continues with a complete memory example. It checks guest pointer-length pairs, demonstrates that `Read` returns a copy, and shows that an out-of-bounds `Write` changes nothing. --- Source page: https://docs.wago.sh/canary/guides/embed/guest-memory Markdown: https://docs.wago.sh/raw/canary/guides/embed/guest-memory.md # Exchange bytes with a guest WebAssembly pointers are offsets into linear memory. A pointer-length pair needs a bounds check before Go can use it, even when the guest normally sends a valid string. This example gives the guest one 64 KiB memory page. The guest calls `env.write`, and the host copies the requested bytes before printing them. You will also try an invalid range and see how checked host reads behave after a write. Continue in the Go project from [Run WebAssembly from Go](./runtime-and-modules). This example needs WABT's `wat2wasm`, regardless of your earlier guest language. Create `guest/message.wat`: ```wat (module (import "env" "write" (func $write (param i32 i32) (result i32))) (memory (export "memory") 1 1) (data (i32.const 0) "hello from wasm") (func (export "say") (result i32) i32.const 0 i32.const 15 call $write) (func (export "write_range") (param i32 i32) (result i32) local.get 0 local.get 1 call $write)) ``` ```sh wat2wasm guest/message.wat -o message.wasm ``` Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("message.wasm") if err != nil { return err } imports := wago.NewImports() imports.HostFunc("env", "write", func(caller wago.Caller, call wago.HostCall) { ptr := uint32(call.I32(0)) length := uint32(call.I32(1)) memory := caller.Memory() end := uint64(ptr) + uint64(length) if end > uint64(len(memory)) { call.SetI32(0, -1) return } data := append([]byte(nil), memory[uint64(ptr):end]...) fmt.Printf("guest says %q\n", data) call.SetI32(0, int32(length)) }).Params(wago.ValI32, wago.ValI32).Results(wago.ValI32) runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module, wago.WithImports(imports)) if err != nil { return err } defer instance.Close() out, err := instance.InvokeContext(ctx, "say") if err != nil { return err } fmt.Println("bytes written:", wago.AsI32(out[0])) // -1 encodes the unsigned pointer 0xffffffff. Adding 2 in a uint32 // would wrap to 1 and could make an unsafe range appear valid. out, err = instance.InvokeContext(ctx, "write_range", wago.I32(-1), wago.I32(2)) if err != nil { return err } fmt.Println("invalid range:", wago.AsI32(out[0])) saved, ok := instance.Read(0, 15) if !ok { return fmt.Errorf("could not read guest message") } if !instance.Write(0, []byte("Hello")) { return fmt.Errorf("could not update guest message") } current, ok := instance.Read(0, 15) if !ok { return fmt.Errorf("could not read updated message") } fmt.Printf("saved copy: %q\n", saved) fmt.Printf("current memory: %q\n", current) // The last byte exists, but a two-byte write would cross the boundary. fmt.Println("out-of-bounds write accepted:", instance.Write(65535, []byte{1, 2})) last, ok := instance.ReadUint8(65535) if !ok { return fmt.Errorf("could not read last byte") } fmt.Println("last byte:", last) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text guest says "hello from wasm" bytes written: 15 invalid range: -1 saved copy: "hello from wasm" current memory: "Hello from wasm" out-of-bounds write accepted: false last byte: 0 ``` ## Keep borrowed memory inside the callback `Caller`, `HostCall`, its parameter and result slot slices, and `Caller.Memory()` are borrowed for the synchronous callback. They must not escape into a goroutine or be used after the callback returns. Copy bytes into Go-owned storage if you need to retain them. Check the range before making that copy. The guest and host agree here that `-1` means an invalid range. Wago does not assign that status meaning; your ABI does. A real host writer may also need a smaller application-level length limit and rules for encoding, partial writes, or errors. ## Use checked copies outside callbacks `Instance.Read` returns a copy. `Instance.Write` checks the entire range before changing memory. The example's failed write therefore leaves the last byte untouched. Typed helpers such as `ReadUint32Le` and `WriteUint32Le` use little-endian scalar values. `Instance.Memory().UnsafeBytes()` is a mutable, zero-copy view. Its lifetime is your responsibility: it does not keep the instance open or make concurrent guest and host access safe. Do not retain it across calls that may grow memory, shutdown, or operations you do not control. Prefer the checked copy helpers for ordinary application code. These convenience helpers address memory 0 with 32-bit offsets. For indexed memory or Memory64, design that ABI explicitly and use the plugin guest-storage interfaces described in [plugin host imports](../plugins/authoring/host-imports). --- Source page: https://docs.wago.sh/canary/guides/embed/host-functions Markdown: https://docs.wago.sh/raw/canary/guides/embed/host-functions.md # Let Wasm call Go Continue in the `wago-embed` project from [Run WebAssembly from Go](./runtime-and-modules), with its `guest` directory and Go module. If you choose TinyGo again, replace the earlier `guest/main.go` with the new guest below. A host function supplies an import declared by the guest. Start with an ordinary typed Go function; use the lower-level `HostFunc` form only when the callback needs the calling instance or its memory. ## Bind a typed function The guest declares `host.mul(i32, i32) -> i32`, then uses it to implement `square`. Pick the language you want to embed. ### WAT Create `guest/square.wat`: ```wat (module (import "host" "mul" (func $mul (param i32 i32) (result i32))) (func (export "square") (param $value i32) (result i32) local.get $value local.get $value call $mul)) ``` ```sh wat2wasm guest/square.wat -o square.wasm ``` ### AssemblyScript Create `guest/square.ts`: ```ts @external("host", "mul") declare function mul(a: i32, b: i32): i32; export function square(value: i32): i32 { return mul(value, value); } ``` ```sh npx --yes --package assemblyscript@0.28.8 asc \ guest/square.ts --runtime stub --optimize --noAssert \ --outFile square.wasm ``` ### TinyGo Create `guest/main.go`: ```go //go:build tinygo package main //go:wasmimport host mul func mul(a, b int32) int32 //go:wasmexport square func square(value int32) int32 { return mul(value, value) } func main() {} ``` ```sh tinygo build -target=wasm-unknown -no-debug \ -o square.wasm ./guest ``` Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "slices" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("square.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() imports := wago.NewImports() imports.HostFunc("host", "mul", func(a, b int32) int32 { return a * b }) instance, err := runtime.Instantiate( ctx, module, wago.WithImports(imports), ) if err != nil { return err } defer instance.Close() if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeContext(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeContext(ctx, "square", wago.I32(9)) if err != nil { return err } fmt.Println(wago.AsI32(results[0])) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 81 ``` `HostFunc` keeps the Wasm module name and field name separate, so it remains unambiguous even when either contains a dot. Wago checks the Go function against the guest's declared signature during instantiation. Configure an import collection before first use; instantiation seals it, after which it can be reused concurrently but cannot be modified. WAT spells the import directly, AssemblyScript uses `@external`, and TinyGo uses `//go:wasmimport`. All three produce the same WebAssembly boundary, so the host binding does not change. ## Read caller memory [Exchange bytes with a guest](./guest-memory) is a complete runnable version of this pattern, including a pointer-overflow attempt and checked host reads and writes. Pointer-length pairs from a guest are untrusted. Use the caller-aware `HostCall` form when a callback needs guest memory: ```go imports := wago.NewImports() imports.HostFunc("env", "write", func(caller wago.Caller, call wago.HostCall) { ptr := uint32(call.I32(0)) length := uint32(call.I32(1)) memory := caller.Memory() end := uint64(ptr) + uint64(length) if end > uint64(len(memory)) { call.SetI32(0, -1) return } data := append([]byte(nil), memory[ptr:end]...) fmt.Printf("guest says %q\n", data) call.SetI32(0, int32(length)) }).Params(wago.ValI32, wago.ValI32).Results(wago.ValI32) ``` Pass the collection during instantiation: ```go wago.WithImports(imports) ``` Use a wider integer for `ptr + length` so the addition cannot wrap before the bounds check. `HostCall`, its raw slot views, the memory view, and `Caller` are valid only during the callback. Copy anything that must survive it, and do not send borrowed values to another goroutine. ## Re-enter Wasm deliberately A caller-aware callback may synchronously invoke an export through `InvokeFromHost` while its `Caller` is active: ```go out, err := instance.InvokeFromHost(ctx, caller, "normalize", wago.I32(value)) ``` Use this only for guest APIs that require synchronous re-entry. The caller token is scoped to the callback and fails closed after it returns. One invocation chain may have at most four active `InvokeFromHost` calls across all instances; a fifth returns `wago.ErrPermissionDenied`. Each call still performs lifecycle admission, and no `WasmFunc` keeps an instance reserved between calls. ## Define failures deliberately Wasm has no built-in Go `error` result. Prefer an explicit guest ABI such as a numeric status, a sentinel result, or an output buffer. When the callback cannot continue the current invocation, abort it with the original error: ```go panic(wago.HostTrap{Err: err}) ``` Wago recovers `HostTrap` at the native boundary and returns its error to the caller. An unexpected Go panic is a programming failure, not a guest error channel. Host functions run as trusted Go in your process. Give each closure the narrowest interface it needs. Runtime policy limits declared guest capabilities and resources; it does not sandbox the Go callback itself. --- Source page: https://docs.wago.sh/canary/guides/embed/limits-and-policy Markdown: https://docs.wago.sh/raw/canary/guides/embed/limits-and-policy.md # Add limits and cancellation There are three separate boundaries: - `RuntimeConfig` controls compilation and runtime-wide resource ceilings. - `Policy` checks one module when an instance is created. - `context.Context` controls how long instantiation and calls may continue. ## Run with explicit boundaries Use the `module.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "fmt" "log" "os" "slices" "time" "github.com/wago-org/wago" ) func run() error { wasm, err := os.ReadFile("module.wasm") if err != nil { return err } config := wago.NewRuntimeConfig(). WithMaxModuleBytes(16<<20). WithMemoryLimitPages(256). WithMaxFunctionLocals(4096). WithInstanceLimits(8, 0) if err := config.Validate(); err != nil { return err } runtime := wago.NewRuntime(wago.WithRuntimeConfig(config)) defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() policy := wago.Policy{ MaxMemories: 1, MaxTableEntries: 1024, } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() instance, err := runtime.Instantiate(ctx, module, wago.WithPolicy(policy)) if err != nil { return err } defer instance.Close() if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeContext(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeContext(ctx, "add", wago.I32(20), wago.I32(22)) if err != nil { return err } fmt.Println(wago.AsI32(results[0])) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text 42 ``` `WithMaxModuleBytes` rejects oversized input before compilation. `WithMemoryLimitPages` caps the live size of each linear memory. `WithInstanceLimits` bounds simultaneously live direct instances; a closed instance returns its admission budget. `Policy` is an admission check against the module's declared capabilities and limits. The zero policy is permissive. A non-empty `AllowedCapabilities` list is exclusive, and `DeniedCapabilities` always wins. A `MaxMemoryBytes` policy also requires the module to declare a finite maximum. `Policy.MaxInvokeDuration` is retained for compatibility but is not enforced: a nonzero value is rejected with `wago.ErrUnsupported`. Use a context deadline for call duration. ## Handle cancellation and failures `InvokeContext` and `InvokeValues` return `context.Canceled` or `context.DeadlineExceeded` when the supplied context interrupts guest execution: ```go if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("guest exceeded its deadline: %w", err) } ``` Policy failures wrap `wago.ErrPermissionDenied`. Runtime traps can be inspected without matching error text: ```go var trap *wago.TrapError if errors.As(err, &trap) { log.Printf("guest trapped: %s", trap.Code) } ``` A context can interrupt Wasm execution, but it cannot forcibly make arbitrary Go code return. Host functions that may block should accept a bounded dependency or cooperate with cancellation. Truly hostile blocking code needs process isolation. ## Interrupt a guest that does not return A fast `add` call rarely reaches its deadline. This test needs WABT's `wat2wasm`, regardless of your earlier guest language. To check your actual cancellation path, create `guest/loop.wat`: ```wat (module (func (export "spin") (loop $again br $again)) (func (export "answer") (result i32) i32.const 42)) ``` ```sh wat2wasm guest/loop.wat -o loop.wasm ``` Replace `main.go` with this complete program. Instantiation happens outside the short call deadline, so the timeout tests guest execution rather than setup: ```go package main import ( "context" "errors" "fmt" "log" "os" "time" "github.com/wago-org/wago" ) func run() error { wasm, err := os.ReadFile("loop.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(context.Background(), module) if err != nil { return err } defer instance.Close() ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() _, err = instance.InvokeContext(ctx, "spin") if !errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("expected deadline exceeded, got %v", err) } fmt.Println("spin stopped at its deadline") out, err := instance.InvokeContext(context.Background(), "answer") if err != nil { return err } fmt.Println("next call:", wago.AsI32(out[0])) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` ```sh go run . ``` ```text spin stopped at its deadline next call: 42 ``` Cancellation does not roll back memory or globals, and it does not automatically close the instance. Use a new instance if your application needs a clean state after an interrupted call. Native cancellation is supported on amd64 and arm64 with standard Go, or TinyGo with `-scheduler=threads`. Other TinyGo schedulers reject cancelable native calls before entering the guest. On Linux/amd64 with standard Go, interruption uses a thread-directed signal; other supported targets stop at native safepoints. Do not turn a deadline into a hard wall-clock guarantee for arbitrary host callbacks. `Runtime.Compile` does not take a context. Apply compilation-size and resource limits before accepting untrusted modules, and account for compilation separately from invocation timeouts. --- Source page: https://docs.wago.sh/canary/guides/embed/runtime-and-modules Markdown: https://docs.wago.sh/raw/canary/guides/embed/runtime-and-modules.md # Run WebAssembly from Go Start here when Wago should live inside your Go process. You will build the same guest in WAT, AssemblyScript, or TinyGo, then compile it, create an instance, and call its `add` export from Go. ## Create a small project Install [Go 1.22 or newer](https://go.dev/dl/) and the tools for your guest language before creating the project: - **WAT:** [WABT](https://github.com/WebAssembly/wabt), with `wat2wasm` on your `PATH`. The later state, memory, and cancellation examples also use WAT, so install this to follow the whole embedding section. - **AssemblyScript:** Node.js 20 or newer and npm 10 or newer. The commands below download the pinned AssemblyScript 0.28.8 compiler with `npx`. - **TinyGo:** [TinyGo](https://tinygo.org/getting-started/install/) and a Go version that it supports, both on your `PATH`. Select that Go version before `go mod init`; a newer Go release can be too new for TinyGo. The examples were also checked with TinyGo 0.41.1 and Go 1.25.0. You need network access for the Go module download and, for AssemblyScript, the first `npx` command. The embedding programs do not require the Wago CLI. ```sh mkdir wago-embed cd wago-embed go mod init example.com/wago-embed go get github.com/wago-org/wago@main mkdir guest ``` This canary guide uses `@main`. `@latest` selects a tagged release, which may have a different API; use that release's documentation when you choose it. For a deployed application, pin a release tag or commit and keep `go.mod` and `go.sum` with your application. Check what was selected with: ```sh go list -m github.com/wago-org/wago ``` Run this guide and the following embedding pages from the `wago-embed` directory. Each complete Go program replaces `main.go`; do not keep multiple copies of `main` in the project. Keep the generated Wasm files for the later pages. Pick a guest language. Each version exports the same WebAssembly function. ### WAT Create `guest/add.wat`: ```wat (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) ``` Build it: ```sh wat2wasm guest/add.wat -o module.wasm ``` ### AssemblyScript Create `guest/add.ts`: ```ts export function add(a: i32, b: i32): i32 { return a + b; } ``` Build it with a pinned compiler: ```sh npx --yes --package assemblyscript@0.28.8 asc \ guest/add.ts --runtime stub --optimize --noAssert \ --outFile module.wasm ``` ### TinyGo Create `guest/main.go`: ```go //go:build tinygo package main //go:wasmexport add func add(a, b int32) int32 { return a + b } func main() {} ``` Build it: ```sh tinygo build -target=wasm-unknown -no-debug \ -o module.wasm ./guest ``` Create `main.go`: ```go package main import ( "context" "fmt" "log" "os" "slices" "github.com/wago-org/wago" ) func run(ctx context.Context) error { wasm, err := os.ReadFile("module.wasm") if err != nil { return err } runtime := wago.NewRuntime() defer runtime.Close() module, err := runtime.Compile(wasm) if err != nil { return err } defer module.Close() instance, err := runtime.Instantiate(ctx, module) if err != nil { return err } defer instance.Close() // TinyGo reactors initialize their runtime through this export. WAT and // AssemblyScript modules in this example do not emit it. if slices.Contains(module.Exports(), "_initialize") { if _, err := instance.InvokeContext(ctx, "_initialize"); err != nil { return err } } results, err := instance.InvokeContext( ctx, "add", wago.I32(20), wago.I32(22), ) if err != nil { return err } fmt.Println(wago.AsI32(results[0])) return nil } func main() { if err := run(context.Background()); err != nil { log.Fatal(err) } } ``` Run it: ```sh go run . ``` ```text 42 ``` `InvokeContext` takes raw WebAssembly value slots. `wago.I32` encodes an `i32`, and `wago.AsI32` reads one back. These helpers do not change the guest signature. The returned slice belongs to the instance until its next call; copy any results you want to keep. [Calls and state](./calls-and-state) covers the typed API and other scalar types. The guest language changes how you produce `module.wasm`, not how you embed it. The Go side sees the same WebAssembly types and export name in every case. TinyGo's `_initialize` export is the one lifecycle difference in this example; call it once per new instance before calling your own exports. ## Know what you own `Runtime` owns shared compiler resources, plugins, and lifecycle state. `Module` holds validated native code that can be reused. `Instance` owns mutable guest state such as memory, tables, and globals. Instantiation runs a WebAssembly start section, if present. Exports such as `_start`, `main`, and `_initialize` are separate functions: the Go API does not choose and call them for you. This example invokes `_initialize` only when the guest exports it. Create the runtime and compile the module once. Create instances according to the lifetime of the guest state you need, and close all three resources when you are finished. From here, choose the part your application needs: - [Calls and state](./calls-and-state) for values, memory, globals, and instance lifetime. - [Guest memory](./guest-memory) for a complete pointer-length exchange and checked memory copies. - [Host functions](./host-functions) when Wasm needs to call your Go code. - [Limits and cancellation](./limits-and-policy) before running untrusted modules. - [Concurrency and shutdown](./services-and-concurrency) for a long-lived service. - [Precompiled artifacts](./artifacts) when startup compilation is too expensive. --- Source page: https://docs.wago.sh/canary/guides/embed/services-and-concurrency Markdown: https://docs.wago.sh/raw/canary/guides/embed/services-and-concurrency.md # Run Wago in a service Compile during service startup, then give each concurrent request its own instance. The requests share native code while keeping guest memory, tables, and globals isolated. Use the `module.wasm` from [Run WebAssembly from Go](./runtime-and-modules). Replace `main.go` with: ```go package main import ( "context" "errors" "fmt" "log" "os" "slices" "sort" "sync" "time" "github.com/wago-org/wago" ) type Service struct { runtime *wago.Runtime module *wago.Module } func NewService(wasm []byte) (*Service, error) { runtime := wago.NewRuntime() module, err := runtime.Compile(wasm) if err != nil { _ = runtime.Close() return nil, err } return &Service{runtime: runtime, module: module}, nil } func (s *Service) Add(ctx context.Context, a, b int32) (int32, error) { instance, err := s.runtime.Instantiate(ctx, s.module) if err != nil { return 0, err } defer instance.Close() if slices.Contains(s.module.Exports(), "_initialize") { if _, err := instance.InvokeContext(ctx, "_initialize"); err != nil { return 0, err } } results, err := instance.InvokeContext(ctx, "add", wago.I32(a), wago.I32(b)) if err != nil { return 0, err } return wago.AsI32(results[0]), nil } func (s *Service) Close(ctx context.Context) error { return errors.Join(s.module.Close(), s.runtime.CloseContext(ctx)) } type response struct { line string err error } func run() error { wasm, err := os.ReadFile("module.wasm") if err != nil { return err } service, err := NewService(wasm) if err != nil { return err } defer func() { _ = service.Close(context.Background()) }() jobs := [][2]int32{{1, 2}, {3, 4}, {20, 22}} responses := make(chan response, len(jobs)) var group sync.WaitGroup for _, value := range jobs { group.Add(1) go func() { defer group.Done() result, err := service.Add(context.Background(), value[0], value[1]) responses <- response{ line: fmt.Sprintf("add(%d, %d) = %d", value[0], value[1], result), err: err, } }() } group.Wait() close(responses) var lines []string for result := range responses { if result.err != nil { return result.err } lines = append(lines, result.line) } sort.Strings(lines) for _, line := range lines { fmt.Println(line) } shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() return service.Close(shutdown) } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` Run the program normally, then with Go's race detector. The second command needs a platform supported by Go's race detector, cgo enabled, and a C compiler on `PATH`; the ordinary embedding program does not require a C compiler. ```sh go run . go run -race . ``` ```text add(1, 2) = 3 add(20, 22) = 42 add(3, 4) = 7 ``` Calls on an individual instance are serialized, including while a call is inside a host callback. Separate instances allow independent requests to run concurrently. The race-enabled command runs this actual program; `go test -race` alone would not exercise a project with no tests. Create a fresh instance per request when state should not survive. If state must persist, assign that instance to one worker and serialize access to it. At shutdown, stop admitting requests, wait for active calls, close persistent instances, close modules, and then call `Runtime.CloseContext`. `Runtime.Close` starts shutdown and may finish asynchronously when callbacks or active work are involved; use `CloseContext` when the service must wait for the final result. ## Choose what can survive a request A fresh instance starts with the module's initial memory, tables, and globals. The compiled module is reusable, but a `.wago` artifact does not save a running instance's state. Wago currently has no public instance snapshot, restore, reset, or ready-made instance pool API. If you keep a worker's instance alive, its mutations survive every call, including mutations made before an error or cancellation. Only reuse it across requests when that is part of the guest's contract. For request isolation, instantiate again from the same module. The isolation in this example covers guest-owned state. Explicitly imported memory or tables can be shared, and host callbacks may close over shared Go state. Protect that state with the same synchronization you would use in any other concurrent Go code. ## Wait for shutdown without deadlocking `Instance.Close` publishes a logical close: new calls fail, while admitted work and close callbacks finish before resources are reclaimed. Use `Instance.WaitClosed(ctx)` after `Close` for the close operation's result. It does not wait for physical release still held by active calls or retained references; drain your application's calls separately. A cached `WasmFunc` does not keep a closed instance callable. Call `Runtime.Close` from a callback that needs to initiate shutdown. Waiting there with `CloseContext` or `WaitClosed` can wait for the callback itself. Do the waiting from your application's shutdown path after stopping incoming requests. If `CloseContext` reaches its deadline, shutdown continues. Keep track of the runtime and use `WaitClosed` later to observe the final outcome; a timeout is not proof that every callback has stopped. --- Source page: https://docs.wago.sh/canary/guides/plugin-authoring Markdown: https://docs.wago.sh/raw/canary/guides/plugin-authoring.md # Author Wago plugins A Wago plugin is a Go package linked into a generated runtime. It can define host imports, observe or intercept runtime work, manage instances, transform modules, extend the compiler, or provide a typed service to another plugin. Start small. One definition, one provider, and one useful registration are enough for a real plugin. ## Start here ### [Write your first plugin](./plugins/authoring/first-plugin) Scaffold a module, define one host import, generate its catalog, and test it. ### [Definitions and providers](./plugins/authoring/definitions-and-providers) Describe what the plugin is, what it needs, and how Wago creates it. ### [Testing](./plugins/authoring/testing) Check definitions, registration, catalog drift, and clean installation. ### [Publish](./plugins/publish) Tag an open-source module and send its verified snapshot to the registry. ## Before you begin Complete [Getting started](../getting-started) to install the manager and select a standard runtime. The first-plugin walkthrough also needs Go 1.22 or newer on `PATH`. It starts from an empty directory; you do not need to clone Wago or publish a package to run its tests. The later pages show focused code fragments, rather than cumulative edits to the answer plugin. The runnable examples on later pages include commands pinned to the public revision tested for this walkthrough. Those `go run ...@revision` commands work outside a Wago checkout and do not install plugins into your selected CLI runtime. The examples include their compiled Wasm guests. ## Pick one next step - To give Wasm a function, read [Host imports](./plugins/authoring/host-imports). - To call it from a guest, compare [WAT, AssemblyScript, and TinyGo](./plugins/authoring/guest-languages). - To own work or observe calls, read [Lifecycle and hooks](./plugins/authoring/lifecycle-and-hooks). - To accept settings, read [Configuration](./plugins/authoring/configuration). - To connect plugins, read [Contracts and dependencies](./plugins/authoring/contracts). - To host a WIT interface or a Preview 2 command, read [Component Model](./components). - To extend compilation, start with [Custom instructions](./plugins/authoring/custom-instructions), then [Custom types](./plugins/authoring/custom-types). Each privileged handle needs an exact publisher-authored Authority request and a consumer-reviewed grant. If your plugin only needs a host import, do not ask for instance management or runtime hooks. ## Trust boundary Plugins run as native Go code in the host process. Authorities limit access to Wago's privileged integration APIs; they do not sandbox file access, network access, process state, or other Go behavior. Keep the source public, keep dependencies narrow, and review plugins as native dependencies. The complete runnable set lives in [Wago's examples directory](https://github.com/wago-org/wago/tree/main/examples). --- Source page: https://docs.wago.sh/canary/guides/plugins Markdown: https://docs.wago.sh/raw/canary/guides/plugins.md # Use plugins This tutorial adds a plugin to a local Wago project and keeps the result reproducible. Use your own `module.wasm`; the plugin you choose must provide the imports or runtime features that module needs. The workflow is: ```text Project → add plugin → review access → build runtime → run module ``` Plugins are Go packages compiled into the Wago runtime. Review them as native dependencies, even when their requested Wago Authorities are narrow. If you want a complete guest to start with, [Using plugins](../using-plugins) downloads and runs a small WASI command. Continue with [WASI configuration](./wasi) for arguments, environment, I/O, and files, or [Component Model](./components) for typed component calls from Go. ## Follow the tutorial - [Create a local project and add a plugin](./plugins/install-and-scope). - [Review the dependency graph, grants, and lockfile](./plugins/grants-and-lockfiles). - [Run the module, update the plugin, and rebuild from the lockfile](./plugins/update-and-rebuild). At the end, the project has a reviewed plugin runtime, a manifest that records what you requested, and a lockfile that can reproduce the exact build. Browse available packages at [plugins.wago.sh](https://plugins.wago.sh). --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/configuration Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/configuration.md # Configure a plugin Configuration lives in the reviewed lock entry. The definition describes its shape; the plugin reads the selected value. ## Define the Go shape ```go type Config struct { Prefix string `json:"prefix"` SampleRate int `json:"sampleRate"` } ``` ## Publish a schema Set `PluginDefinition.ConfigSchema` to a JSON Schema. Reject unknown fields and bound numbers and strings where you can. ```go ConfigSchema: json.RawMessage(`{ "type":"object", "additionalProperties":false, "properties":{ "prefix":{"type":"string","maxLength":32}, "sampleRate":{"type":"integer","minimum":1,"maximum":1000} } }`), ``` The schema describes the public configuration, but the current runtime does not automatically enforce every JSON Schema constraint on the selected value. Implement the actual bounds and semantic checks in `PluginProvider.ValidateConfig` or during registration. Do not rely on `minimum`, `maximum`, or string-length metadata alone to reject a value. ## Read the value ```go cfg := Config{SampleRate: 10} if err := reg.Config(&cfg); err != nil { return err } ``` `Config` rejects unknown struct fields and trailing JSON. Initialize defaults before decoding so an omitted field keeps its default while an explicit zero is still rejected by the bounds check: ```go if cfg.SampleRate < 1 || cfg.SampleRate > 1000 { return fmt.Errorf("sampleRate must be between 1 and 1000") } if utf8.RuneCountInString(cfg.Prefix) > 32 { return fmt.Errorf("prefix must be at most 32 characters") } ``` This uses `fmt` and `unicode/utf8`. Put the same checks in a shared decoding helper if both `ValidateConfig` and `Register` need them. The complete flow is in [examples/09-plugin-config-lifecycle](https://github.com/wago-org/wago/tree/main/examples/09-plugin-config-lifecycle). ## Change configuration These CLI commands apply to an already installed provider in a consumer project. `github.com/acme/wago-metrics` is a placeholder, not a package supplied by this guide; replace it with your published provider ID and use its actual schema. For an unpublished local plugin, set `PluginSelection.Config` in the Go integration test and call `LoadPlugins` there. Pass the complete configuration as JSON: ```sh wago plugin config github.com/acme/wago-metrics \ '{"prefix":"demo","sampleRate":10}' ``` For a larger value, save the JSON in `metrics-config.json`: ```sh wago plugin config github.com/acme/wago-metrics --file metrics-config.json ``` This replaces the selected configuration; it does not merge fields. Omitting both JSON and `--file` sets `{}`. It does not open an editor. Review the resulting `wago-lock.json` change, then run a representative guest. The CLI checks JSON syntax and rebuilds the runtime, but plugin-specific validation runs when the plugin is loaded. A successful configuration command alone does not prove that startup will succeed. Keep the previous JSON so you can restore it with the same command. For a real provider with environment, I/O, and filesystem settings, follow [Configure WASI](../../wasi). Run the published example without a source checkout: ```sh go run github.com/wago-org/wago/examples/09-plugin-config-lifecycle@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/contracts Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/contracts.md # Contracts and dependencies Use a Contract when one plugin needs a Go service from another. ## Name the service Put the interface and Contract value in a small package both plugins import. The typed helpers are in `github.com/wago-org/wago/plugin`; alias that import as `pluginapi` so it does not collide with the scaffold's `type plugin`: ```go import pluginapi "github.com/wago-org/wago/plugin" ``` ```go type Clock interface { UnixMillis() int64 } var Contract = pluginapi.NewContract[Clock]( "github.com/acme/wago-clock/service", 1, ) ``` Change the major when providers and consumers can no longer share the same Go interface. ## Provide it List `Contract.Spec()` in `PluginDefinition.Provides`. During registration, provide the value: ```go return pluginapi.Provide[Clock](reg, Contract, clock) ``` Use the explicit `[Clock]` type argument when `clock` has a concrete implementation type. Without it, Go can infer conflicting types from the Contract and value arguments. ## Require it List the provider under `PluginDefinition.Requires` and a requirement under `Consumes`: ```go Requires: []wago.PluginRequirement{{ ID: "github.com/acme/wago-clock", Version: "^1.0.0", }}, Consumes: []wago.ContractRequirement{{ ID: Contract.ID(), Major: Contract.Major(), Mode: wago.ContractRequired, }}, ``` Then get the typed reference during `Register`: ```go clock, err := pluginapi.Require(reg, Contract) if err != nil { return err } ``` Use the service inside `With` after registration has committed. For startup work, register a lifecycle callback; calling `With` immediately inside `Register` fails because the Contract is not active yet: ```go return reg.Lifecycle(wago.PluginLifecycle{ Start: func(context.Context) error { return clock.With(func(service Clock) error { fmt.Println(service.UnixMillis()) return nil }) }, }) ``` This callback uses `context` and `fmt`. `With` keeps the provider alive until the callback returns. Do not retain `service` after it returns. ## Choose a binding Use `pluginapi.Require` when exactly one provider must exist. Use `pluginapi.Optional` when the consumer can work without one. Use `pluginapi.Many` when it needs every selected provider in the reviewed order. The lockfile records exact providers and ordering. Wago rejects missing providers, incompatible majors, duplicate single bindings, unreviewed bindings, and cycles before it calls a plugin factory. Run [examples/13-plugin-contracts](https://github.com/wago-org/wago/tree/main/examples/13-plugin-contracts) for the complete two-plugin graph. Run the published example without a source checkout: ```sh go run github.com/wago-org/wago/examples/13-plugin-contracts@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/custom-instructions Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/custom-instructions.md # Add a custom instruction A custom instruction starts as an ordinary function import. Wago replaces calls to that import while compiling the guest. ## Pick the guest ABI This WAT import carries two four-bit values through normal `i32` parameters: ```wat (import "wago:instr/example.int" "i4.add" (func $i4.add (param i32 i32) (result i32))) ``` Any language that can emit the same import can use it. ## Request the module Request `compiler.instruction.define` with `wago:instr/example.int` in `Scope.Modules`. ## Define its meaning Inside `Register`, get `Registrar.CompilerInstructions`, then define the logical widths and portable handler: ```go instructions, err := reg.CompilerInstructions() if err != nil { return err } return instructions.Define(wago.InstructionSpec{ Module: "wago:instr/example.int", Name: "i4.add", Input: []int32{4, 4}, Output: []int32{4}, Handler: func(_ wago.InstructionContext, in []wago.Bits) ([]wago.Bits, error) { value, err := wago.BitsFromUint32(4, in[0].Uint32()+in[1].Uint32()) return []wago.Bits{value}, err }, }) ``` The handler is the fallback and the executable definition of the operation. ## Add a scalar lowering Add this `Lower` field to the same `InstructionSpec`: ```go Lower: func(ctx wago.LoweringContext) error { ctx.Output(0, ctx.Add(ctx.Input(0), ctx.Input(1))) return nil }, ``` Wago can inline this recipe on supported backends. The portable handler remains available elsewhere. Use target-specific code generation only when the scalar recipe cannot express the operation. Raw AMD64 or ARM64 emission is trusted backend code and needs architecture-tagged files. Run [examples/18-custom-instruction](https://github.com/wago-org/wago/tree/main/examples/18-custom-instruction) for the complete plugin and WAT guest. Run the published example without a source checkout: ```sh go run github.com/wago-org/wago/examples/18-custom-instruction@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/custom-types Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/custom-types.md # Add a custom compiler type Custom types keep plugin-owned values in native registers across a chain of custom instructions. The guest still uses a standard Wasm type such as `externref` for validation. ## Register the type Request `compiler.type.define` for the `example.value` namespace, then define the value: ```go types, err := reg.CompilerTypes() if err != nil { return err } value, err := types.Define(wago.CustomTypeSpec{ Name: "example.value/v256", Size: 32, Carrier: wago.WasmExternRef, }) if err != nil { return err } ``` The size must be positive and 16-byte aligned. ## Use the returned token Also request `compiler.instruction.define` for the exact module containing the producer and consumer instructions (`example:types` in the runnable example). Get `reg.CompilerInstructions()` as in [Custom instructions](./custom-instructions), then add the token to an instruction signature: ```go Custom: &wago.CustomSignature{ Inputs: []wago.CustomType{value, value}, Output: &value, }, ``` The token belongs to that compiler registry. It cannot be forged or moved to another registry. ## Provide native code A custom value has no portable handler. Add target-specific lowerings in `codegen_amd64.go` and `codegen_arm64.go`. The lowering receives and returns the native register bundle through `InputCustom` and `OutputCustom`. Custom values currently have expression lifetime. They can flow directly between custom calls or be dropped. They cannot enter Wasm locals, cross control flow, pass to ordinary functions, or return from the guest. Run [examples/19-custom-type](https://github.com/wago-org/wago/tree/main/examples/19-custom-type). Its WAT guest uses `externref`; the plugin keeps the 256-bit value in one AMD64 YMM register or two ARM64 vector registers. Run the published example without a source checkout: ```sh go run github.com/wago-org/wago/examples/19-custom-type@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/definitions-and-providers Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/definitions-and-providers.md # Definitions and providers Every plugin has an immutable definition and an explicit provider. Wago can review and resolve the definition without constructing the plugin. ## `PluginDefinition` The definition is published metadata, not runtime state. Give it a canonical `ID`, a semantic `Version`, and clear registry text through `Name`, `Description`, and `Stability`. Record where the code came from in `Provenance`, and use `Compatibility` to state which Wago versions and platforms it supports. Add `Requires` for plugin dependencies, `Authorities` for privileged Wago APIs, `ConfigSchema` for user configuration, and `Provides` or `Consumes` for typed Contracts. Leave out sections the plugin does not need. The definition must contain enough information to review the plugin before its code is downloaded or run. Keep reasons concrete: `define the acme_clock guest API` is useful; `needed by the plugin` is not. ## `PluginProvider` The provider connects metadata to code: ```go func Provider() wago.PluginProvider { return wago.PluginProvider{ Definition: Definition, New: func() wago.Plugin { return &plugin{} }, ValidateConfig: validateConfig, } } ``` `New` must return a new plugin value suitable for one runtime load. Put per-runtime mutable state on that value instead of package globals. `ValidateConfig` is optional and handles semantic checks that the published schema cannot express. ## The `/register` catalog A module exposes its providers through a conventional package: ```go // Package register exposes this module's Wago providers. package register func Providers() []wago.PluginProvider { return []wago.PluginProvider{ clock.Provider(), metrics.Provider(), } } ``` Generated runtimes import `/register` and combine its returned values. Do not use `init` to register providers. Hidden global registration makes selection depend on import side effects and prevents an empty runtime from staying empty. One Go module may publish several providers. Give each provider its own canonical ID and version, then return all of them from the root catalog. Use package dependencies when selecting one provider must also select another. ## Keep versions aligned Before a release, these values must agree: - `package.version` in `wago.json`; - every published `PluginDefinition.Version` for that release; - the Git tag, such as `v0.2.0`; and - the committed `wago.providers.json` snapshot. Publication rejects mismatched tagged metadata. Move to a new version instead of rewriting an existing tag. --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/first-plugin Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/first-plugin.md # Write your first plugin This plugin adds `tutorial.answer() -> i32` and returns `42`. You will create its catalog, then test an actual guest call so registration errors cannot hide behind a passing metadata test. You need Go 1.22 or newer on `PATH`, the Wago manager, and a standard runtime. Complete [Getting started](../../../getting-started) first, then check `wago --version`. The walkthrough works with the beta.11 manager and standard runtime; the Go dependency below is pinned separately. ## Start the wizard ```sh mkdir wago-answer cd wago-answer wago init --plugin ``` Choose your public Go module path, name, description, version, license, repository, and author. Use a repository you control for a plugin you intend to publish. The wizard writes `wago.json`, `wago.providers.json`, `go.mod`, `register/register.go`, and a catalog test. The complete [answer fixture](https://github.com/wago-org/docs/tree/c10fc427b008e71878e9cb890e2c609d0f008a8c/demos/fixtures/plugins-walkthrough/answer) uses `github.com/acme/wago-answer` as an example identity. It is local test code, not a package to install from that GitHub account. > **Info — Canary dependency:** The beta.11 scaffold writes `github.com/wago-org/wago v0.1.0`, which is not published. Replace it with the public canary revision used by this walkthrough before generating the catalog: ```sh go mod edit -droprequire github.com/wago-org/wago go get github.com/wago-org/wago@b084a7c9343f81a9120ca80a13d133884e88d514 ``` Go records the exact pseudo-version in `go.mod`. Commit `go.mod` and `go.sum`; no local checkout or `replace` directive is needed. Use a newer revision only after rerunning the same tests. ## Request one Authority Open `register/register.go`. Add this field inside the generated `wago.PluginDefinition`: ```go Authorities: []wago.AuthorityRequest{{ Name: wago.AuthorityHostImportDefine, Mode: wago.AuthorityRequired, Reason: "define the tutorial guest API", Scope: wago.AuthorityScope{Modules: []string{"tutorial"}}, }}, ``` The scope covers the exact import module `tutorial`. It does not cover parent names or wildcards. ## Define the guest function Replace the generated `Register` method with this complete method. Give its registrar parameter the name `reg`: ```go func (plugin) Register(reg *wago.Registrar) error { imports, err := reg.HostImports() if err != nil { return err } imports.HostFunc("tutorial", "answer", func(call wago.HostCall) { call.SetI32(0, 42) }).Results(wago.ValI32) return nil } ``` `HostCall` supplies the result slot. `.Results(wago.ValI32)` declares the guest signature. The current inferred-signature adapter does not accept `func() int32`, so use this portable form for the zero-argument result. ## Refresh and check the catalog ```sh gofmt -w register/register.go wago plugin catalog go test ./... wago plugin catalog --check ``` ![Generating and checking a Wago plugin catalog](/demos/plugin-authoring.gif) The generated test compares metadata with `wago.providers.json`. It does not load the plugin or execute its host function. Add the guest test next. ## Call it from Wasm The guest imports the function and re-exports a wrapper: ```wat (module (import "tutorial" "answer" (func $answer (result i32))) (func (export "run") (result i32) call $answer)) ``` Download the matching precompiled guest into `testdata/answer.wasm`, or build that WAT with your usual guest tools: ```sh mkdir -p testdata curl -fsSL https://raw.githubusercontent.com/wago-org/wago/b084a7c9343f81a9120ca80a13d133884e88d514/examples/22-language-guests/wat/answer.wasm -o testdata/answer.wasm ``` Add `register/integration_test.go`: ```go package register import ( "context" "os" "testing" wago "github.com/wago-org/wago" ) func TestAnswerFromGuest(t *testing.T) { provider := Providers()[0] digest, err := wago.DefinitionDigest(provider.Definition) if err != nil { t.Fatal(err) } set := wago.PluginSet{ Providers: []wago.PluginProvider{provider}, Selections: []wago.PluginSelection{{ ID: provider.Definition.ID, DefinitionDigest: digest, Direct: true, Grants: []wago.AuthorityGrant{{ Name: wago.AuthorityHostImportDefine, Scope: wago.AuthorityScope{Modules: []string{"tutorial"}}, }}, }}, } ctx := context.Background() rt := wago.NewRuntime() defer rt.Close() if err := rt.LoadPlugins(ctx, set); err != nil { t.Fatal(err) } wasm, err := os.ReadFile("../testdata/answer.wasm") if err != nil { t.Fatal(err) } mod, err := rt.Compile(wasm) if err != nil { t.Fatal(err) } defer mod.Close() in, err := rt.Instantiate(ctx, mod) if err != nil { t.Fatal(err) } defer in.Close() results, err := in.Invoke("run") if err != nil { t.Fatal(err) } if len(results) != 1 || wago.AsI32(results[0]) != 42 { t.Fatalf("run() = %v, want 42", results) } } ``` This test explicitly grants the one reviewed Authority. `Direct: true` makes the provider a selected root. The test fails if the grant, callback, Wasm import, or result is wrong. Run both checks: ```sh gofmt -w register go test ./... -v wago plugin catalog --check ``` You should see `TestProviderCatalog` and `TestAnswerFromGuest` pass. These tests link the local provider directly. They do not install it into the `wago` CLI runtime; keep using the Go test until you publish and install your own package. ## Keep going For a complete plugin with a guest capability and state, run [examples/08-custom-plugin](https://github.com/wago-org/wago/tree/main/examples/08-custom-plugin). You can run the published example without cloning Wago: ```sh go run github.com/wago-org/wago/examples/08-custom-plugin@b084a7c9343f81a9120ca80a13d133884e88d514 ``` Read [Definitions and providers](./definitions-and-providers) to grow this definition, then [Test a plugin](./testing) before publishing. --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/guest-languages Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/guest-languages.md # Call a plugin from guest code Plugin imports are ordinary Wasm functions. Use the syntax your guest language already provides for imported functions. This example calls `tutorial.answer() -> i32`. ### WAT ```wat (module (import "tutorial" "answer" (func $answer (result i32))) (func (export "run") (result i32) call $answer)) ``` ### AssemblyScript ```ts @external("tutorial", "answer") declare function answer(): i32; export function run(): i32 { return answer(); } ``` ### TinyGo ```go //go:wasmimport tutorial answer func answer() int32 //go:wasmexport run func run() int32 { return answer() } ``` The module name, function name, parameters, and results must match the plugin declaration. Run [examples/22-language-guests](https://github.com/wago-org/wago/tree/main/examples/22-language-guests) to execute all three compiled guests against one host function. Run the pinned example directly from any directory: ```sh go run github.com/wago-org/wago/examples/22-language-guests@b084a7c9343f81a9120ca80a13d133884e88d514 ``` Expect `WAT answer = 42`, `AssemblyScript answer = 42`, and `TinyGo answer = 42`. Its build script reproduces the checked-in `.wasm` files. ## Check the guest before loading it From the `wago-answer` directory created in [Write your first plugin](./first-plugin), inspect the downloaded guest: ```sh wago module imports testdata/answer.wasm wago module exports testdata/answer.wasm ``` Expect an import named `tutorial.answer` with signature `() -> i32` and an exported `run`. An `unresolved` import is expected here: the local Go test has not installed a CLI plugin. Run the local provider through its integration test: ```sh go test ./register -run TestAnswerFromGuest -v ``` After publishing and [installing your own plugin](../install-and-scope) into the selected CLI runtime, the equivalent command is: ```sh wago run testdata/answer.wasm --invoke run ``` The result is `42`. `--invoke run` selects the same export consistently, including guests with several exports. Wago can auto-select the WAT example's sole `run` function even though it has no `_start`. TinyGo reactor-style guests may also export `_initialize`. Call it once before `run` on the same instance when the guest needs initialization: ```sh wago run path/to/tinygo/answer.wasm --invoke _initialize --invoke run ``` The checked-in language example handles that initialization for its TinyGo guest. The build script requires the matching guest toolchains; the Go test uses the existing binaries and does not need to install them. --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/host-imports Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/host-imports.md # Add host imports A host import is a Go function called by Wasm. The plugin's `host.import.define` grant names the exact import modules it may add. ## Get the registrar ```go imports, err := reg.HostImports() if err != nil { return err } ``` Return `err` before registering functions. A grant for `acme_math` does not cover a parent, child, or wildcard name; flat registration preserves the exact module and function identity. ## Write the callback ```go func addOne(value int32) int32 { return value + 1 } ``` Ordinary supported Go signatures are inferred without runtime reflection. The adapter supports a fixed set of signatures; it does not accept every Go function with Wasm-compatible types. Use `func(wago.HostCall)` for arbitrary supported scalar/reference arity, or `func(wago.Caller, wago.HostCall)` when the callback needs guest state. For example, use the portable callback for a no-argument function returning `i32`: ```go imports.HostFunc("acme_math", "answer", func(call wago.HostCall) { call.SetI32(0, 42) }).Results(wago.ValI32) ``` A plain `func() int32` is not a supported inferred signature. Registration reports `unsupported host callback` for it. ## Declare its Wasm signature ```go imports.HostFunc("acme_math", "add_one", addOne). Params(wago.ValI32). Results(wago.ValI32) ``` Wago checks that signature against the importing module. ## Guest memory `Caller.Memory()` returns memory 0 for the duration of a caller-aware callback. Check the range before slicing and do not retain the slice, `Caller`, or `HostCall`. ```go memory := caller.Memory() offset := uint64(uint32(call.I32(0))) if offset >= uint64(len(memory)) { return } ``` Use `GuestStorageHostModule` for indexed memory, Memory64 metadata, exact GC types, or Wasm GC arrays. [examples/21-guest-storage](https://github.com/wago-org/wago/tree/main/examples/21-guest-storage) shows the checked borrow. ## Guest capabilities Register a capability when the import gives Wasm a permission the host may deny: ```go err := reg.GuestCapability( wago.Capability("clock.read"), wago.CapabilityDocs("read the host clock"), ) ``` Handle that error, then attach the capability to the function builder. Declaring a capability alone does not require it for an import: ```go if err != nil { return err } imports.HostFunc("acme_clock", "now_millis", func(call wago.HostCall) { call.SetI64(0, time.Now().UnixMilli()) }).Results(wago.ValI64).Capability(wago.Capability("clock.read")) ``` This callback imports `time`; the definition and reviewed grant must include `acme_clock` in the `host.import.define` module scope. The guest capability governs Wasm. The Plugin Authority governs trusted Go plugin code. Run [examples/08-custom-plugin](https://github.com/wago-org/wago/tree/main/examples/08-custom-plugin) for a complete import and capability. Run the published examples without a source checkout: ```sh go run github.com/wago-org/wago/examples/08-custom-plugin@b084a7c9343f81a9120ca80a13d133884e88d514 go run github.com/wago-org/wago/examples/21-guest-storage@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/lifecycle-and-hooks Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/lifecycle-and-hooks.md # Lifecycle and hooks `Register` builds a plan. It should decode configuration and declare contributions, without starting work that must later be undone. ## Add lifecycle callbacks Keep the registration small: ```go return reg.Lifecycle(wago.PluginLifecycle{ Start: p.start, Stop: p.stop, }) ``` Both callbacks receive a `context.Context` and return an error. `Start` runs after Wago accepts the full plugin plan. Start listeners, files, and goroutines there. `Stop` also runs after a partially failed `Start`. Check which resources exist, stop accepting work, wake blocked callbacks, and release each resource once. See [examples/09-plugin-config-lifecycle](https://github.com/wago-org/wago/tree/main/examples/09-plugin-config-lifecycle) for a runnable lifecycle. ## Choose a hook Use `RuntimeCloseObserver` when runtime shutdown matters. Module work belongs in `ModuleSourceTransformer`, `ModuleCompileObserver`, or `ModuleCloseObserver`. Their Authorities are `runtime.close.observe`, `module.source.transform`, `module.compile.observe`, and `module.close.observe`. For instances, an interceptor can reject work or attach state; an observer records the result. Use `InstanceInstantiateInterceptor` or `InstanceInstantiateObserver` while creating an instance, and `InstanceInvokeInterceptor` or `InstanceInvokeObserver` around calls. `InstanceCloseObserver` handles exact-instance close. Request only the matching Authority: `instance.instantiate.intercept`, `instance.instantiate.observe`, `instance.invoke.intercept`, `instance.invoke.observe`, or `instance.close.observe`. ## Observe a call Get the observer during registration: ```go calls, err := reg.InstanceInvokeObserver() if err != nil { return err } ``` Attach the callback: ```go return calls.After(func(event wago.InvocationEvent) { log.Printf("%s: %v", event.Export, event.Err) }) ``` Observers record outcomes. Interceptors may return an error to stop an operation. Use opaque event identities to correlate state instead of retaining a `Runtime`, `Module`, or `Instance`. Run [examples/10-hooks](https://github.com/wago-org/wago/tree/main/examples/10-hooks) to see the complete compile, instantiate, invoke, close, and runtime-close order. Run the published examples without a source checkout: ```sh go run github.com/wago-org/wago/examples/09-plugin-config-lifecycle@b084a7c9343f81a9120ca80a13d133884e88d514 go run github.com/wago-org/wago/examples/10-hooks@b084a7c9343f81a9120ca80a13d133884e88d514 ``` --- Source page: https://docs.wago.sh/canary/guides/plugins/authoring/testing Markdown: https://docs.wago.sh/raw/canary/guides/plugins/authoring/testing.md # Test a plugin Test one boundary at a time. Most plugin mistakes appear before a Wasm module runs. ## Test ordinary Go code ```sh go test ./... ``` Keep parsing, state, and service logic outside `Register`. Then those parts need no Wago test setup. If callbacks share state, run: ```sh go test -race ./... ``` ## Test registration Build a `PluginSet` with the same definition, grants, configuration, dependencies, and Contract bindings a consumer will review. Then validate it: ```go if err := wago.ValidatePluginSet(reviewedSet()); err != nil { t.Fatal(err) } ``` Add a case for each optional Authority you can run without. Add a scope-boundary case for modules or instance budgets. The runnable examples use [examples/internal/exampleplugin](https://github.com/wago-org/wago/tree/main/examples/internal/exampleplugin) to keep this setup out of each `main.go`. That is a Go `internal` package and cannot be imported by an external plugin module. Use the explicit `PluginSet` from [the first-plugin integration test](./first-plugin#call-it-from-wasm) in your own module. ## Execute a guest A catalog test can pass while `Register` still fails. Include a small Wasm fixture that imports the plugin's function, load the reviewed `PluginSet`, instantiate the guest, and check its return value. [Write your first plugin](./first-plugin#call-it-from-wasm) includes a complete test. A selection for a standalone provider needs `Direct: true`; dependency-only providers must be reachable from a reviewed direct root. A digest and grant alone do not make a provider reachable. ## Check the catalog After changing a definition, refresh its snapshot: ```sh wago plugin catalog ``` CI should only check for drift: ```sh wago plugin catalog --check ``` Commit `wago.providers.json` with the code it describes. ## Test shutdown For a plugin with lifecycle work, cover: - normal `Start` and `Stop`; - a partially completed `Start`; - cancellation during startup; - an active callback during close; and - release of every plugin-owned resource. Use a deadline for tests that wait on goroutines. ## Try the consumer path First [publish a release of your own plugin](../publish). The `github.com/acme/wago-answer` name below is a placeholder, not a published package; replace it with your real module path. Publishing and registry submission are separate from the local authoring checks above. After your release is available, use a new directory: ```sh mkdir consumer-test cd consumer-test wago init --run ``` Add the plugin interactively: ```sh wago add github.com/acme/wago-answer ``` Read the review Wago shows, run a small guest, and rebuild once from the lockfile: ```sh wago plugin rebuild --locked ``` Run the guest again after rebuilding. Also test configuration changes with a real load: `wago plugin config` may successfully rebuild a configuration that the provider rejects at startup. A clean directory catches missing release files and accidental module-cache dependencies. An unpublished local provider should use Go tests or a Go host that links its provider directly; the public install path requires a published release. --- Source page: https://docs.wago.sh/canary/guides/plugins/faq Markdown: https://docs.wago.sh/raw/canary/guides/plugins/faq.md # Plugin FAQ ### Do I need a plugin for every Wasm module? No. Modules that only use core WebAssembly can run with the bare runtime. Inspect a module first: ```sh wago module imports module.wasm ``` Add a plugin when those imports or another runtime feature need one. ### Why does WASI come from a plugin? WASI is a host interface, not a core WebAssembly instruction set. Keeping it in a plugin lets a project choose the WASI version and capabilities it needs without adding them to every Wago runtime. ### Do plugins require Go? Yes. Wago compiles selected plugins into a project or global runtime. Install Go 1.22 or newer before adding or rebuilding plugins. ### Why does adding a plugin take longer than running a module? `wago add` resolves packages, checks definitions and grants, downloads Go modules, generates a runtime, and builds it. Later runs reuse that built runtime until the selected graph changes. ### Should I install a plugin locally or globally? Use local scope for a project you may share or deploy. Its manifest and lockfile travel with the repository. Use global scope for personal tools you want in unrelated directories. ### Are plugins sandboxed? No. Plugins are native Go dependencies in the host process. Authorities limit their access to privileged Wago handles, but ordinary Go code can still use the operating system and process APIs available to the host. ### What is an Authority? An Authority is one exact privileged Wago integration, such as defining imports in a named module or observing invocations. The publisher requests it with a reason and scope; the consumer reviews the grant during installation. ### What happens if I deny a required Authority? Wago leaves the previous runtime and project state in place. You can narrow a required scope, but registration fails if the plugin cannot work within that grant. Optional Authorities may be omitted. ### How are guest capabilities different from plugin Authorities? A plugin Authority controls what trusted Go plugin code may add to Wago. A guest capability controls what a Wasm module may use through the host. A filesystem plugin may need `host.import.define` while exposing `fs.read` and `fs.write` to guest policy. ### Why are there two JSON files? `wago.json` records direct project intent and version ranges. `wago-lock.json` records exact sources, checksums, definitions, grants, configuration, dependencies, and Contract bindings. Commit both for local projects. ### Can I edit wago-lock.json by hand? Do not edit digests, checksums, grants, or bindings to silence a failure. Use `wago add`, `wago plugin grant`, `wago plugin config`, `wago plugin update`, or `wago rm`, then review the generated diff. ### Why does a plugin expose a register package? Generated runtimes import `/register` and call `Providers()` to collect explicit provider values. Wago does not use hidden process-global registration from `init`. ### Can one repository publish several plugins? Yes. Give each provider a canonical package ID and immutable definition, then return the providers from the module's root catalog. The root package can also act as an aggregate that selects subpackages. ### Can a plugin add custom Wasm instructions? Yes. The guest imports an ordinary function, and a plugin with `compiler.instruction.define` supplies its semantics and compiler lowering. Start with [Custom instructions](./authoring/custom-instructions). ### What is a custom compiler type? It is a plugin-owned value that stays in native registers between custom instruction calls. The guest uses a standard carrier such as `externref`; no new Wasm binary type is required. See [Custom types](./authoring/custom-types). ### Which guest languages can use a plugin? Any language that can emit the plugin's ordinary Wasm imports. The examples include [WAT, AssemblyScript, and TinyGo](./authoring/guest-languages). ### Where does plugin configuration live? The selected JSON value lives in the plugin entry in `wago-lock.json`. Change it with `wago plugin config '{"key":"value"}'` or `--file config.json`; do not put plugin-owned settings under the core `settings` object in `wago.json`. The value replaces the existing configuration. Omitting it sets `{}`. Run a guest afterward to check provider-specific validation and startup. ### When should two plugins use a Contract? Use a Contract when one plugin needs a typed Go service from another. Keep the interface small, give it a stable ID and incompatible major version, and access values only through the leased `With` callback. ### Does inspection run plugin code? `wago plugin inspect`, `wago plugin list --json`, and immutable plan inspection read definitions and reviewed selections without calling factories, `Register`, `Start`, or `Stop`. ### How do I test an unpublished plugin? Run normal Go tests, validate a `PluginSet` with `wago.ValidatePluginSet`, and check the generated catalog. The public CLI install path needs a published module release, so test that path from a clean project after pushing a test version. ### Can the public registry host a private plugin? No. Registry releases point to public source and are verified from the tagged Go module. An embedder can link its own provider catalog directly in Go, but that is a separate deployment path from registry installation. ### Why did a locked rebuild fail after an update? The manifest, module cache, provider catalog, definition, grant, configuration, or Contract binding no longer matches the committed graph. Run a networked update, review and commit the result, then retry `wago plugin rebuild --locked`. ### How do I remove a plugin? Run: ```sh wago rm github.com/acme/plugin ``` Wago removes transitive plugins that no other direct requirement needs and asks you to review any changed Contract bindings. --- Source page: https://docs.wago.sh/canary/guides/plugins/grants-and-lockfiles Markdown: https://docs.wago.sh/raw/canary/guides/plugins/grants-and-lockfiles.md # Review the install Adding the plugin created two files. `wago.json` records the plugin and version range you requested. `wago-lock.json` records the exact source, checksums, dependencies, grants, configuration, and Contract bindings Wago built. Commit both files. Review their diff whenever the plugin graph changes. ## Inspect the graph Show every direct and transitive plugin: ```sh wago plugin tree ``` Inspect one installed plugin: ```sh wago plugin inspect ``` Choose a plugin in the interactive picker. Check its repository, version, dependencies, requested Authorities, reasons, scopes, and Contract bindings. Inspection reads built metadata without starting plugin lifecycle code. An Authority grants access to one privileged Wago integration API. It does not sandbox the plugin's ordinary Go code. If the request is broader than the plugin's job, cancel the install or edit the grant: ```sh wago plugin grant ``` The interactive editor can narrow requested modules and resource limits or deny optional access. It cannot grant access the publisher did not request or widen a scope beyond that request. Next, [run the module and maintain the plugin runtime](./update-and-rebuild). --- Source page: https://docs.wago.sh/canary/guides/plugins/install-and-scope Markdown: https://docs.wago.sh/raw/canary/guides/plugins/install-and-scope.md # Add a plugin You need an active Wago runtime and Go 1.22 or newer. Complete [Getting started](../../getting-started) first if `wago status` does not show a runtime. Start in the directory that contains your `module.wasm`. Initialize a local project: ```sh wago init ``` Select **Run WebAssembly**. Wago creates `wago.json` in the current directory. Inspect the module before choosing a plugin: ```sh wago module imports module.wasm ``` Find a package that provides those imports at [plugins.wago.sh](https://plugins.wago.sh), then add it. For a module that imports Wide's `as-simd` functions: ```sh wago add JairusSW/wide ``` Review the source and requested access in the interactive security screen, then confirm the build. Wago leaves the old project state in place if resolution or compilation fails. The nearest `wago.json` makes this a local install. Local plugins travel with the project and are the right default for repositories you share or deploy. Global plugins are intended for personal tools used across unrelated directories. Confirm that the plugin was built: ```sh wago plugins list ``` ## Choose the scope deliberately From a project directory, `wago add` uses its nearest `wago.json`. You can make the choice explicit: ```sh wago add --local wago-org/wasi/p1 ``` For a personal runtime shared by unrelated directories: ```sh wago add --global wago-org/wasi/p1 ``` A project's local graph takes precedence over the global graph. They are not merged. Select the runtime you want for one invocation: ```sh wago run --local module.wasm wago run --global module.wasm wago run --bare module.wasm ``` `--bare` selects no plugins. It is useful for checking that a module only needs core WebAssembly. It will not satisfy WASI or other host imports. ## Select a provider and version A package can contain several providers. For example, the WASI root offers a choice between the bundle and individual previews. An explicit provider path skips that picker: ```sh wago add wago-org/wasi/p1 ``` To constrain updates, quote the complete package spec: ```sh wago add 'wago-org/wasi/p1@^0.3.1' ``` The manifest keeps the range; the lockfile keeps the selected release. In non-interactive use, a root package selects its whole bundle. Choose a provider path when you only need that provider. Next, [review exactly what Wago installed](./grants-and-lockfiles). --- Source page: https://docs.wago.sh/canary/guides/plugins/publish Markdown: https://docs.wago.sh/raw/canary/guides/plugins/publish.md # Publish a Wago plugin Package a reusable Wago plugin, preview exactly what will ship, then publish it to the public plugin registry. New plugin authors should finish [Write your first plugin](./authoring/first-plugin) and [Test a plugin](./authoring/testing) before tagging a release. Publishing requires a public GitHub repository and a Wago registry account. The dry run works before login. ## Prepare the plugin ```sh wago init --plugin ``` Skip this command if the plugin already exists. The wizard collects the package metadata and creates the release files. A publishable manifest points to public source and keeps discovery metadata under `package`. Wago plugins are open source. Declare every privileged Wago integration as an exact Authority with a human reason and enforceable scope. Declare package requirements separately from typed, major-versioned Contracts. Provider catalogs return values from `Providers()`; they never self-register from `init`. ## Sign in ```sh wago auth login ``` ## Refresh the catalog ```sh wago plugin catalog ``` Run the plugin tests. Then check that no definition changed during the test run: ```sh wago plugin catalog --check ``` ## Commit and tag ```sh git add wago.json wago.providers.json register git commit -m "Prepare plugin v0.1.0" ``` Tag that commit and push it: ```sh git tag v0.1.0 git push origin HEAD v0.1.0 ``` The version in the tag, manifest, and definitions must match. ## Preview publication ```sh wago plugin publish --dry-run ``` ## Publish ```sh wago plugin publish ``` The publish dry run only prints the planned mutation. Actual publishing first checks the local catalog against the committed snapshot, then downloads the exact tagged Go module. Its `wago.json` package metadata and `wago.providers.json` must match the local release, and its `h1:` checksum is sent with the request. Local code runs only for the local drift check; Wago does not execute code from the downloaded tag. The registry independently downloads that same exact module and checksum, reads both artifacts without executing plugin code, and rejects any mismatch. Consumers later review the stored immutable definitions before plugin code is downloaded or built; linked definitions must match their reviewed digests. --- Source page: https://docs.wago.sh/canary/guides/plugins/update-and-rebuild Markdown: https://docs.wago.sh/raw/canary/guides/plugins/update-and-rebuild.md # Run and maintain the plugin Wago finds the nearest `wago.json` and uses its generated runtime automatically. Run your module: ```sh wago run module.wasm ``` If the module still reports a missing import, compare `wago module imports module.wasm` with `wago plugins list` and return to the plugin review. ## Check for updates ```sh wago plugin outdated ``` This does not change the project. To update the selected plugin graph: ```sh wago plugin update ``` Follow the same interactive review used during installation. Wago asks again when an update adds or widens access or changes Contract bindings. Review the `wago.json` and `wago-lock.json` diff before committing it. ## Rebuild from the lockfile ```sh wago plugin rebuild ``` This rebuilds the runtime from the exact versions, checksums, grants, configuration, and Contract bindings in `wago-lock.json`. ## Remove a plugin ```sh wago rm JairusSW/wide ``` Wago removes transitive dependencies that nothing else needs and asks you to review changed Contract bindings. The project is now portable: commit `wago.json` and `wago-lock.json`, then run `wago plugin rebuild` after cloning it elsewhere. See [Automation and Go](../../reference/configuration/automation-and-go) for non-interactive CI checks, or the [Plugin FAQ](./faq) for scopes, configuration, and troubleshooting. --- Source page: https://docs.wago.sh/canary/guides/wasi Markdown: https://docs.wago.sh/raw/canary/guides/wasi.md # Run a WASI command [Using plugins](../using-plugins) gets a Preview 1 hello-world running. Here you will build your own command, pass it arguments, and choose which host resources it can see. You need a standard Wago runtime, Go 1.22 or newer, and a project directory with `wago.json`. ## Choose the preview Add the provider that matches the guest: - **Preview 1** imports the core module `wasi_snapshot_preview1`. Use `wago add wago-org/wasi/p1` and `wago run`. - **Preview 2** uses component interfaces such as `wasi:cli/run`. Use the typed command service described in [Component Model](./components#run-a-preview-2-command). The root `wago-org/wasi` bundles both previews. An interactive root install offers a provider choice; a non-interactive root install selects everything. Preview 1 alone does not activate the Component Model provider. WASI and Component Model support are experimental. Preview 1 supports Wago's six desktop OS/architecture pairs. Preview 2 currently excludes `darwin/amd64`; check the provider's platform declaration before choosing a deployment target. ## Build a small command Save this as `main.go` in your project: ```go package main import ( "fmt" "os" "strings" ) func main() { fmt.Println("args:", strings.Join(os.Args[1:], ", ")) fmt.Println("greeting:", os.Getenv("GREETING")) } ``` Build it for WASI Preview 1: ::: code-group ```sh [macOS / Linux] GOOS=wasip1 GOARCH=wasm go build -o command.wasm main.go ``` ```powershell [Windows] $env:GOOS = 'wasip1' $env:GOARCH = 'wasm' go build -o command.wasm main.go Remove-Item Env:GOOS, Env:GOARCH ``` > **The — environment overrides apply to the guest build. Clear them before Wago builds native plugins.:** If this is a new directory, initialize it and install Preview 1: ```sh wago init --run wago add wago-org/wasi/p1 ``` Review the source and four requested Authorities: defining imports in exactly `wasi_snapshot_preview1`, identifying callers, reading guest arguments, and observing instance close. These grants let the plugin integrate with Wago. The plugin still runs as native Go code. ## Pass arguments Inspect the imports, then run the command: ```sh wago module imports command.wasm wago run command.wasm alpha beta ``` Expected output: ```text args: alpha, beta greeting: ``` The file path is `argv[0]`; the trailing values become the remaining guest arguments. To pass a guest argument that looks like a Wago flag, use `--`: ```sh wago run command.wasm -- --help ``` The guest prints `args: --help`. Core exports with parameters still use Wago's typed invocation rules; this example runs a no-argument `_start` command. ## Choose environment values WASI starts with an empty guest environment. It does not inherit the host process environment. Save `wasi-config.json`: ```json { "env": ["GREETING=hello from Wago"] } ``` Apply it and run again: ```sh wago plugin config github.com/wago-org/wasi/p1 --file wasi-config.json wago run command.wasm alpha beta ``` Expected output: ```text args: alpha, beta greeting: hello from Wago ``` Configuration is a complete replacement. Include every setting you want to keep when changing the JSON. Commit the reviewed lockfile, but do not put secrets in a committed `env` value. > **Warning — Check startup after a configuration change:** The command rebuilds the runtime, but provider-specific validation happens when the plugin loads. Run a small guest after changing settings. If it fails, restore the last working JSON with `wago plugin config ... --file`. Running `wago plugin config ` without a JSON value or file sets `{}`. It does not prompt for configuration. ## Choose streams By default, stdin, stdout, and stderr are attached to the host process. Pipe input and redirect output in the shell as usual. For a guest that must not wait for input, add `"stdin": "eof"` to its configuration. To suppress an output stream, use `"stdout": "discard"` or `"stderr": "discard"`. Keep output inherited while debugging so you can see the guest's diagnostics. ## Grant a directory There are no filesystem mounts by default. For a guest that reads `/data`, create a host directory and add a rights-bearing mount to the configuration. Replace the host path with your directory's clean absolute path: ```json { "env": ["GREETING=hello from Wago"], "mounts": [ { "guest": "/data", "host": "/absolute/path/to/guest-data", "read": true } ], "maxOpenFiles": 256 } ``` On Windows, use a native absolute host path such as `C:\\guest-data` in JSON. The guest path remains `/data`. - `read` permits reads and metadata beneath the mounted directory. - `write` permits file writes and related metadata changes. - `mutateDirectory` permits creating, removing, and renaming directory entries. No rights are implied by the other fields. Add write or directory-mutation access only when the guest needs it. Host paths must exist and name directories. The guest cannot escape the mounted directory through path traversal or a symlink. Whether a safe internal symlink or `..` path is accepted depends on the preview and host filesystem implementation. A guest may request more WASI descriptor rights than its high-level operation suggests. In the walkthrough, Go 1.27's `os.ReadFile` requested rights beyond a read-only mount and received `Capabilities insufficient`. Diagnose the requested rights before widening access; a read-only task should keep a read-only grant. See [WASI access failures](../troubleshooting/plugins-and-builds#wasi-access-fails). ## Keep the runtime reproducible ```sh wago plugin tree wago plugin inspect github.com/wago-org/wasi/p1 wago plugin rebuild --locked wago run command.wasm alpha beta ``` Commit `wago.json` and `wago-lock.json`. The lockfile records the exact provider, configuration, and reviewed Authorities. Preview 1 commands can also be compiled into a [standalone executable](./cli/standalone). For Preview 2 components or custom WIT exports, continue with [Component Model](./components). --- Source page: https://docs.wago.sh/canary/ Markdown: https://docs.wago.sh/raw/canary/index.md # Welcome to Wago Glad you're here! ## What is Wago? Wago is a wonderfully quick, compact, and extensible WebAssembly runtime for Go. A quote has stuck with me throughout the project: > “Fast hardware should bring excellence, not reason to waste it.” We built Wago around this idea. Because of it, we pushed to cut overhead, memory use, and bloat instead of hiding them behind faster hardware. Our goal is to make Wago as fast and capable as possible without ever letting it grow wasteful. The community should shape Wago too. Its plugin system lets users supply imports, control code generation, and even add custom WebAssembly features. Plugins can take Wago in new directions without forcing every new idea into the core runtime. ## What's in the box? We wanted Wago to be wonderful to use, so we've actually added quite a bit. - **Runtime and compiler**: execute Wasm, save precompiled `.wago` files, or build standalone executables for AMD64 and ARM64. - **Plugins**: extend the runtime with literally anything. Host capabilities, compiler hooks, and custom WebAssembly features all fit here. - **Manager**: install, swap, and update Wago runtimes across beta, canary, or a specific commit. - **Registry**: discover and publish extensions at [plugins.wago.sh](https://plugins.wago.sh). - **Go API**: compile once, create isolated instances, call typed exports, access guest state, and honor cancellation inside your own process. ## Digging in ### [Run a Wasm file](./getting-started) Install Wago, choose a runtime, and run a real module before moving on to the full CLI guide. ### [Embed Wago in Go](./guides/embed/runtime-and-modules) Keep a runtime in your process, reuse compiled modules, and create isolated guest instances. ### [Connect Wasm to Go](./guides/embed/host-functions) Bind reflection-free host functions and exchange values through checked guest memory. ### [Extend Wago with plugins](./using-plugins) Add WASI and run your first module with host capabilities, then explore the full plugin system. --- Source page: https://docs.wago.sh/canary/reference/configuration Markdown: https://docs.wago.sh/raw/canary/reference/configuration.md # Configuration Wago layers configuration from broad defaults to one command: 1. Runtime defaults. 2. User-wide configuration. 3. Project settings in `wago.json`. 4. Explicit command flags. ## Pick a topic ### [Scopes and settings](./configuration/scopes-and-settings) Inspect, set, reset, and preview stable or experimental values. ### [Project manifest](./configuration/project-manifest) Configure features, optimizations, workers, and project plugins in `wago.json`. ### [Automation and Go](./configuration/automation-and-go) Isolate state, install completions, use locked modes, and configure the Go API. --- Source page: https://docs.wago.sh/canary/reference/configuration/automation-and-go Markdown: https://docs.wago.sh/raw/canary/reference/configuration/automation-and-go.md # Configure CI, shells, and the Go API Keep automation isolated from your normal Wago install, remove prompts from scripts, add shell completions, and set runtime policy from Go. ## Isolate Wago state Set `WAGO_HOME` to place manager configuration, installed runtimes, and caches under one root: ```sh WAGO_HOME="$PWD/.wago-ci" wago version current ``` Give concurrent CI jobs separate directories. Inspect paths rather than guessing: ```sh wago status --json wago version which wago cache dir ``` ## Automation flags | Flag | Meaning | |---|---| | `--no-input` | Never prompt; fail if input is missing | | `--dry-run` | Show a supported mutation plan | | `--json` | Emit machine-readable output where supported | | `--locked` | Refuse manifest or lockfile changes | | `--offline` | Use installed and cached resources only | For a prepared repeatable build: ```sh wago run --locked --offline --invoke fib fib.wasm 20 ``` Describe the command surface programmatically: ```sh wago commands --json ``` ## Shell completions ```sh wago config completions zsh wago config completions zsh --install ``` Use `--output` for a specific completion file and `--rc` for a particular startup file. Preview installation with `--dry-run`. ## Go API Use `RuntimeConfig` for compiler policy and `WithPolicy` for per-instance guest limits. The runnable configuration example is in [Create runtimes and modules](../../guides/embed/runtime-and-modules). --- Source page: https://docs.wago.sh/canary/reference/configuration/project-manifest Markdown: https://docs.wago.sh/raw/canary/reference/configuration/project-manifest.md # Configure `wago.json` `wago.json` combines sparse project runtime settings with plugin requirements: ```json { "$schema": "https://wago.sh/v1/schema.json", "settings": { "features": { "simd": true }, "optimizations": { "inline-loop-callees": false }, "runtime": { "parallel": "auto", "deferredBoundsChecking": true } }, "plugins": { "github.com/wago-org/wasi": "^0.1.0" } } ``` Add the schema URI for editor completion and typo detection. The draft-2020-12 schema rejects unknown fields. Create a minimal project: ```sh wago init --run ``` ## Feature settings `settings.features` enables or disables WebAssembly feature families. The runtime defaults to its supported Core 3 feature set; `--core 2` selects the narrower Core 2 compatibility profile for commands that expose it. Use individual settings when a project needs a narrower feature policy. ## Optimization settings ```json { "settings": { "optimizations": { "inline": false } } } ``` The names match CLI switches such as `--no-inline`. Architecture-specific optimizations may not exist on another target. ## Runtime settings `settings.runtime.parallel` accepts `"auto"` or a non-negative worker count encoded as a string. - `"auto"` uses adaptive work. - `"1"` forces serial function work. - A larger number sets a maximum. `deferredBoundsChecking` controls whether Wago may omit explicit checks already proven redundant. ## Plugins and lockfile state `plugins` maps canonical Go module or package paths to semantic-version ranges. Exact direct and transitive sources, checksums, release fingerprints, definition digests, dependency edges, requested and granted Authorities, Contract bindings, and opaque plugin configuration belong in `wago-lock.json`. Ranges support exact, comparator, caret, tilde, partial/x, hyphen, intersection, and `||` union forms. Relative aliases are invalid: use `github.com/wago-org/wasi`, not `wago-org/wasi`. Commit both files. Keep plugin configuration out of `settings`; it belongs to the plugin's reviewed lock entry. ## Publish metadata When the manifest describes a publishable plugin, public metadata lives under a `package` object: ```json { "$schema": "https://wago.sh/v1/schema.json", "package": { "module": "github.com/acme/wago-observability", "version": "0.1.0", "name": "Wago Observability", "description": "Tracing and metrics for Wago runtimes.", "license": "Apache-2.0", "repository": "https://github.com/acme/wago-observability", "authors": [ { "name": "Example Maintainer", "github": "example" } ] } } ``` Provider definitions, Authorities, configuration schemas, and Contracts are not duplicated by hand in this file. Publishing obtains them from the module's explicit `/register` catalog and stores their canonical digests beside the release. The committed module-root `wago.providers.json` is the immutable catalog snapshot. Generate it with `wago plugin catalog`, verify it in CI with `wago plugin catalog --check`, and commit it before creating the release tag. It uses `https://wago.sh/v1/providers.schema.json`. See [Publish a plugin](../../guides/plugins/publish) for the complete workflow. --- Source page: https://docs.wago.sh/canary/reference/configuration/scopes-and-settings Markdown: https://docs.wago.sh/raw/canary/reference/configuration/scopes-and-settings.md # Configure global and project settings Inspect the effective value first, then decide whether the change belongs to the whole machine or only the current project. ## Inspect effective configuration ```sh wago config wago config list wago config list --json wago config diff ``` Inside a project, configuration commands use local scope by default. Be explicit in scripts: ```sh wago config list --local wago config list --global ``` ## Get and set one value ```sh wago config get optimizations.inline wago config set optimizations.inline off --local wago config set optimizations.inline on --global ``` Boolean values accept `on`/`off`, `true`/`false`, `yes`/`no`, and `1`/`0`. ## Reset inheritance ```sh wago config reset optimizations.inline --local wago config reset --all --local ``` Resetting a local value removes the override. The project inherits the global value again. ## Precedence --- Source page: https://docs.wago.sh/canary/troubleshooting Markdown: https://docs.wago.sh/raw/canary/troubleshooting.md # Troubleshooting Most failures happen at a boundary. Start by recording the selected manager, runtime, project, plugins, and module requirements: ```sh wago --version wago status wago version current wago version which ``` ## Pick the failing boundary ### [Installation and runtimes](./troubleshooting/installation-and-runtimes) Fix `PATH`, missing runtimes, wrong variants, and stale compiled artifacts. ### [Modules and calls](./troubleshooting/modules-and-calls) Diagnose validation, missing imports, exports, arguments, and feature sets. ### [Plugins and builds](./troubleshooting/plugins-and-builds) Separate plugin resolution, authorization, lockfile, and standalone build failures. ### [Go API and memory](./troubleshooting/go-api-and-memory) Fix host signatures, pointer-length checks, cancellation, and instance use. ## Report an issue Include the exact command, complete error, OS, architecture, selected runtime, module SHA-256, and the smallest module that reproduces it. Open an issue at [github.com/wago-org/wago/issues](https://github.com/wago-org/wago/issues). --- Source page: https://docs.wago.sh/canary/troubleshooting/go-api-and-memory Markdown: https://docs.wago.sh/raw/canary/troubleshooting/go-api-and-memory.md # Fix Go API and guest memory problems Start at the host-to-Wasm boundary: import signatures, checked memory ranges, context cancellation, and instance ownership. ## The example does not compile Check the dependency selected in your Go project: ```sh go list -m github.com/wago-org/wago ``` The canary [embedding walkthrough](../guides/embed/runtime-and-modules) uses `go get github.com/wago-org/wago@main`. `@latest` selects a tagged release, so use the matching release docs or deliberately update your dependency. Run each complete program as a replacement for `main.go`, not alongside another example that also declares `main`. If TinyGo reports an unsupported Go version, put a Go version supported by your TinyGo release on `PATH` before creating the project. A `go.mod` created with a newer Go version can also force a newer toolchain. Check `go version`, `tinygo version`, and the `go` directive in `go.mod`; do not assume every Go version above Wago's minimum is supported by TinyGo. ## Host import mismatch Both the module name and field name must match the guest, including case. Create imports with `wago.NewImports()` and register callbacks with `imports.HostFunc(module, name, fn)`. Module and function names remain separate exact identities. Wago checks the callback and declared signature before guest startup. If you have the [Wago CLI installed](../getting-started), inspect the module first. For the guest from [Host functions](../guides/embed/host-functions): ```sh wago module imports square.wasm ``` Then compare the parameter and result slots with the guest declaration. Typed callbacks infer their signatures. With `func(wago.HostCall)` or `func(wago.Caller, wago.HostCall)`, set `.Params(...)` and `.Results(...)` explicitly. Build the whole collection before its first instantiation: imports are sealed on first use and cannot be modified afterward. If a later instance needs different bindings, create another collection. ## Guest memory range failure Treat pointers as offsets. Validate addition in a wider integer: ```go end := uint64(ptr) + uint64(length) if end > uint64(len(memory)) { return fmt.Errorf("out of bounds") } data := memory[uint64(ptr):end] ``` Outside host callbacks, prefer checked instance helpers: ```go data, ok := inst.Read(ptr, length) if !ok { return fmt.Errorf("out of bounds") } ``` `Caller.Memory()`, `HostCall`, and its raw slot views are valid only during that synchronous callback. Copy bytes that must survive it. [Exchange bytes with a guest](../guides/embed/guest-memory) is a complete example, including the pointer-overflow case. Do not call the ordinary public invocation path synchronously from a callback on the active instance. Use `InvokeFromHost` with that callback's active `Caller`, otherwise the call can wait for itself. ## Cancellation does not stop work Use a context-aware call: ```go out, err := inst.InvokeContext(ctx, "work", slots...) ``` If you specifically use the typed API: ```go out, err := inst.InvokeValues(ctx, "work", values...) ``` The context needs a deadline or cancel function, and the same context must reach Wago. A background context has no cancellation signal. Blocking Go work in a host function must cooperate with cancellation; the guest deadline cannot make arbitrary Go code return. On TinyGo, cancelable native calls require `-scheduler=threads`. See the [runnable cancellation test](../guides/embed/limits-and-policy#interrupt-a-guest-that-does-not-return). Compilation has no context parameter, so a call deadline does not cover `Runtime.Compile`. ## Concurrent instance calls Public calls on one instance are serialized. Create separate instances from the same compiled module for parallel guest work, and synchronize any host state shared by their callbacks. Raw results from `Invoke`, `InvokeContext`, and `WasmFunc.Invoke` are borrowed until the next invocation. Copy them before a later call. If several goroutines share one instance, an application lock must cover both the call and reading or copying its result; Wago's internal call serialization does not protect the returned slice after the call returns. A `.wago` artifact caches compiled code, not an instance's memory or globals. Reusing an instance preserves mutations; creating another instance from the module starts fresh. There is no public instance reset or snapshot API. ## Shutdown timed out `Runtime.Close` starts shutdown and can return before teardown finishes. Use `CloseContext` from the application shutdown path to wait, or `WaitClosed` after shutdown has started. A timed-out waiter does not cancel the remaining teardown. Inside a callback, initiate runtime shutdown with `Close`; do not wait on the callback's own completion. Drain application requests separately from `Instance.WaitClosed`, which does not wait for physical release held by active calls or retained references. ## Report a reduced failure Include the exact command or Go call, complete error, selected runtime, OS, architecture, module hash, and the smallest reproducer. For memory bugs, include the pointer, length, memory size, and guest signature. --- Source page: https://docs.wago.sh/canary/troubleshooting/installation-and-runtimes Markdown: https://docs.wago.sh/raw/canary/troubleshooting/installation-and-runtimes.md # Fix installation and runtime selection Use this page when the shell cannot find Wago, no runtime is active, the wrong build is selected, or a cached artifact became stale. ## The shell cannot find `wago` If installation finished moments ago, open a new terminal. Then locate the executable: ### macOS / Linux ```sh command -v wago ``` ### PowerShell ```powershell Get-Command wago ``` ### Command Prompt ```cmd where wago ``` If nothing appears, check the installation output. An installer that asked you to add `~/.wago/bin` did not change `PATH` automatically; follow the [PATH setup](../getting-started#install-the-manager) before rerunning the installer. If two paths appear, the first one wins; remove or reorder the stale entry. ## No runtime is active The manager intentionally does not bundle one: ```sh wago version install wago version current wago version which ``` Non-interactively: ```sh wago version install --beta --profile standard --build normal --use --no-input ``` ## The wrong variant is active ```sh wago version switch canary --profile standard --build normal ``` `wago version current` reports the selected channel or version, profile, and build. Use `wago --version` for the resolved release and toolchain. ## The installer is building from source This can happen when the selected release asset or its checksum cannot be fetched. It is slower than a binary download. Check that `go version` and `git --version` work, and retain the complete error if the source build fails. A successful manager install still needs a runtime selected afterward. ## Standard commands are missing Check the profile in `wago --version`. The minimal runtime is run-only. Switch to `standard/normal` for inspection, validation, and precompilation. [Profiling](../guides/cli/profiling) requires a separate opt-in build. Use the matching docs version and the installed command's `--help` when a flag is missing. ## A `.wago` file stopped loading Compiled artifacts are tied to Wago's format and the host architecture. Rebuild from the original Wasm: ```sh wago build fib.wasm -o fib.wago ``` Distribute `.wasm` for portability or use `wago compile` for a target-specific standalone executable. ## Inspect and clean caches ```sh wago cache dir wago cache size wago cache prune --yes ``` Use `wago cache clean` only when you intend to regenerate the selected data. --- Source page: https://docs.wago.sh/canary/troubleshooting/modules-and-calls Markdown: https://docs.wago.sh/raw/canary/troubleshooting/modules-and-calls.md # Fix module, import, export, and call errors Separate decoding, validation, linking, and invocation. The first boundary that fails tells you where to look next. ## Decode or validation failure Separate validation from execution: ```sh wago validate fib.wasm ``` Common causes are malformed bytes, a disabled proposal, a module built for a different WebAssembly feature profile, or a feature unavailable on the selected platform. Wago enables its supported Core 3 feature set by default. Select Core 2 compatibility when the producer or deployment requires that narrower profile: ```sh wago run --core 2 --invoke fib fib.wasm 20 ``` Do not use feature flags to force malformed Wasm through. ## Missing import ```sh wago module imports fib.wasm wago module capabilities fib.wasm ``` An unresolved import means the module needs another plugin scope, an uninstalled plugin, an application host function, or a corrected name and signature. For a local project: ```sh wago init --run wago add github.com/wago-org/wasi wago plugin list ``` For the Go API: ```go imports := wago.NewImports() imports.HostFunc("host", "log", logFunc) instance, err := runtime.Instantiate(ctx, module, wago.WithImports(imports)) ``` ## Missing export Command modules normally export `_start`. Select a library function explicitly: ```sh wago run --invoke missing fib.wasm 20 ``` A source-language function name does not necessarily survive compilation as a Wasm export. ## Rejected arguments Wago follows the Wasm signature. This fails before guest code because `nope` is not an `i32`: ```sh wago run --invoke fib fib.wasm nope ``` Use a value that matches the signature: ```sh wago run --invoke fib fib.wasm 30:i32 ``` In Go, match the declared signature with slot helpers (`wago.I32`, `wago.I64`, `wago.F32`, `wago.F64`). The typed API can also report a type mismatch before running the guest: ```go out, err := inst.InvokeValues(ctx, "add", wago.ValueI32(20), wago.ValueI32(22)) ``` ## A Go embedder never starts the program The CLI chooses an export for you. `Runtime.Instantiate` only runs a WebAssembly start section if one exists; it does not select `_start`, `main`, or `_initialize`. Invoke the entry point the guest toolchain documents. TinyGo reactor guests in the embedding tutorial export `_initialize`, which must run once per instance before your own exports. A guest that uses WASI also needs those imports. A successful `Compile` checks the module, but it does not install a WASI provider or grant filesystem access. ## A raw result changes after another call `Invoke`, `InvokeContext`, and `WasmFunc.Invoke` return instance-owned result slots. Copy a result slice before the next invocation if you need to keep it. `InvokeValues` returns an independently owned typed slice, but is deprecated in favor of the raw APIs for normal invocation; use it deliberately when its typed checks or Runtime invoke hooks are needed. --- Source page: https://docs.wago.sh/canary/troubleshooting/plugins-and-builds Markdown: https://docs.wago.sh/raw/canary/troubleshooting/plugins-and-builds.md # Fix plugin resolution and standalone builds Inspect the selected scope and resolved plugin graph before changing grants, lockfiles, offline mode, or compiler settings. If you need a concept explained rather than an error diagnosed, start with the [Plugin FAQ](../guides/plugins/faq). ## Inspect plugin state ```sh wago status wago plugin tree wago plugin list --json wago plugin inspect github.com/wago-org/wasi wago plugin rebuild --locked ``` Then identify the failing stage: - If `wago.providers.json` is missing or stale, run `wago plugin catalog`, inspect the diff, and commit it before tagging. Use `wago plugin catalog --check` in CI. - If publish reports an exact-source mismatch, the tagged module's `wago.json` or `wago.providers.json` differs from the local release. Move the version forward and create a new tag after committing both artifacts; do not reuse a published Go module version. - `wago plugin outdated` checks for newer releases. - `wago plugin grant github.com/wago-org/wasi` edits reviewed Authority scope. - `wago plugin rebuild` reproduces locked versions. - `wago plugin update github.com/wago-org/wasi` changes resolution and rebuilds. Use `--verbose` when the underlying Go build diagnostic matters. ## A first plugin passes tests but cannot load The scaffold's original test only checks the provider catalog. It does not call `Register`. Add the [guest execution test](../guides/plugins/authoring/first-plugin#call-it-from-wasm). For `unsupported host callback func() int32`, use the portable result-slot callback: ```go imports.HostFunc("tutorial", "answer", func(call wago.HostCall) { call.SetI32(0, 42) }).Results(wago.ValI32) ``` For `selected plugin is unreachable from every reviewed direct root`, mark the intended root selection `Direct: true`, or connect it through a selected consumer's declared dependency. Do not mark every transitive provider direct just to silence the graph check. ## Configuration succeeds but startup fails `wago plugin config` checks JSON syntax and rebuilds. A provider can still reject the value or fail to open a resource when the next runtime loads. Restore your last working configuration and smoke-test it: ```sh wago plugin config github.com/wago-org/wasi/p1 --file wasi-config.json wago run wasi-hello.wasm ``` The value is a complete replacement, not a field merge. Omitting both the JSON argument and `--file` applies `{}`; the command does not open a configuration editor. Unknown WASI fields, relative host paths, missing mount directories, and invalid environment entries are common startup failures. ## A component reports `bad version at offset 4` Check whether the file is a Component Model binary, such as Rust output for `wasm32-wasip2`. The current `wago run` path decodes core Wasm modules. Installing `/p2` does not add component dispatch to that command. Use the [typed Component Model or Preview 2 Go service](../guides/components), or build a Preview 1 command for `wago run`. A real malformed core binary can produce the same decoder error, so verify the guest target before changing plugins. ## WASI access fails - The guest environment is empty unless `env` explicitly supplies values. Exporting a variable in your shell does not pass it to WASI. - Filesystem access needs a configured mount with the required rights. A host path existing on disk is not enough. - `read`, `write`, and `mutateDirectory` are separate. A read grant does not permit creating an output file. - `Capabilities insufficient` can mean the guest requested wider descriptor rights than the mount allows. For example, Go 1.27's Preview 1 `os.ReadFile` requests a broad inheriting-rights mask. Do not widen a read-only mount without checking the guest's needs. - Paths that escape a preopen are denied. Safe internal symlink or `..` behavior depends on the preview and host filesystem implementation; use paths below the intended preopen. - Preview 2 socket and name-lookup interfaces return `access-denied` while networking is disabled. Adding the provider does not grant network access. Review the [WASI configuration walkthrough](../guides/wasi) and the exact provider version in `wago-lock.json`. ## Locked mode fails The operation would need to change `wago.json` or `wago-lock.json`. Preview it outside the final build: ```sh wago plugin update --dry-run --json ``` Review and commit the result, then retry locked mode. Locked mode can also fail when a transitive edge, source checksum, release fingerprint, provider catalog, definition digest, Authority Grant, configuration, or Contract binding no longer matches the committed graph. The locked rebuild identifies the exact field; do not hand-edit a digest or binding to silence it. ## Dependency resolution fails The plan reports every constraint and the parent that contributed it. If no global solution exists, update or remove the conflicting direct requirement rather than forcing one transitive version. Wago backtracks across available releases and prefers the highest deterministic complete solution, so a conflict means the published ranges genuinely cannot be satisfied together. A dependency or Contract cycle is invalid even when every individual range is compatible. Break the package edge or move the shared behavior behind a lower level Contract provider. ## Contract binding fails Check the consumer's Contract ID, major, and mode against the selected provider: ```sh wago plugin list --json ``` Required and optional Contracts accept at most one provider; `many` accepts the complete deterministic provider list. A different major is deliberately incompatible. Locked mode never silently chooses a replacement provider. ## An Authority is denied Inspect the published request and current grant: ```sh wago plugin inspect github.com/wago-org/workers wago plugin grant github.com/wago-org/workers ``` A required Authority must remain present, but its scope can be narrowed. If the plugin needs a withheld module or a larger minimum resource budget, registration or startup fails when the runtime loads. Restore the previous reviewed scope with `wago plugin grant`, then run a representative guest. A grant cannot widen the publisher's request. ## Offline mode fails A required module or artifact is missing locally. Fetch it during an intentional networked preparation step, then run the final build offline. ## Standalone compilation fails Preview the plan: ```sh wago compile fib.wasm --invoke fib --dry-run --json ``` Check that: - `_start` exists or `--invoke` names a real export; - the target is Darwin, Linux, or Windows on AMD64 or ARM64; - required plugins are selected; - every required Contract has its locked provider; - dependencies exist locally when offline mode is enabled; - plugins support the target. Show the Go build output: ```sh wago compile fib.wasm --invoke fib --verbose -o fib ``` --- Source page: https://docs.wago.sh/canary/using-plugins Markdown: https://docs.wago.sh/raw/canary/using-plugins.md # Using plugins Wago keeps host capabilities outside the core runtime. Plugins add the capabilities a module needs without putting every integration into Wago itself. In this guide, you will add WASI Preview 1 support to a local project and run a module that writes to standard output. ![Inspecting an installed Preview 1 provider and running a WASI module](/demos/wasi-command.gif) ## Before you begin You need: - Wago installed with a runtime selected. Complete [Getting started](./getting-started) first if `wago --version` does not show an active runtime. - [Go 1.22 or newer](https://go.dev/doc/install). Wago plugins are Go modules compiled into your runtime. Check both tools from your terminal: ```sh wago --version go version ``` ## Create a local Wago project Create or enter a directory for the example, then initialize it: ```sh mkdir wasi-example cd wasi-example wago init --run ``` This creates a `wago.json` manifest. Keeping the plugin local makes the project's dependencies and reviewed access reproducible instead of changing the runtime used by every project on your machine. ## Add WASI [WASI](https://wasi.dev/) defines system-style interfaces that WebAssembly modules can import. Wago provides those interfaces through the official [wago-org/wasi](https://plugins.wago.sh/wago-org/wasi) plugin: ```sh wago add wago-org/wasi/p1 ``` The `/p1` suffix selects **Preview 1** directly. Adding the root `wago-org/wasi` instead opens a provider picker; a non-interactive root install selects the whole bundle, including Preview 2 and its Component Model dependency. Review the source, dependencies, and requested Authorities before accepting them. Plugins are native Go dependencies; grants control access to privileged Wago integration APIs, but they do not sandbox arbitrary plugin code. Now, check to make sure it is installed: ```sh wago plugins list ``` > A lot of the subcommands have aliases so that it reads naturally. For example, `wago plugin` and `wago plugins` both work the same way. The command updates `wago.json`, writes the complete resolved graph and reviewed grants to `wago-lock.json`, and builds a project runtime. Commit both JSON files with your project. ## Download a WASI module This small module imports WASI Preview 1's `fd_write` function and calls it from `_start`: ```sh curl -fsSL https://wago.sh/corpora/wasi-hello.wasm -o wasi-hello.wasm ``` You can see the import before executing the module: ```sh wago module imports wasi-hello.wasm ``` ## Run it ```sh wago run wasi-hello.wasm ``` You should see: ```text hello from wasi ``` You can even compile it to a standalone executable: ::: code-group ```bash [macOS / Linux] wago compile wasi-hello.wasm -o wasi-hello ./wasi-hello ``` ```powershell [Windows] wago compile wasi-hello.wasm -o wasi-hello.exe .\wasi-hello.exe ``` > **Wago — finds the nearest `wago.json`, selects its project runtime, and uses the WASI plugin to satisfy the module's import.:** ## Where to go next ### [Configure a WASI command](./guides/wasi) Pass arguments, choose environment values, and grant bounded filesystem access. ### [Run a component](./guides/components) Use typed Component Model exports and the Preview 2 command service from Go. ### [Install and choose scope](./guides/plugins/install-and-scope) Learn when to use local, global, or bare plugin selection. ### [Review grants and lockfiles](./guides/plugins/grants-and-lockfiles) Understand Authorities, guest capabilities, dependency graphs, and reproducible builds. ### [Write your own plugin](./guides/plugins/authoring/first-plugin) Scaffold a Go module and add a host import from definition to catalog. ### [Browse plugins](https://plugins.wago.sh) Find published host capabilities and runtime extensions. ### [Troubleshoot a build](./troubleshooting/plugins-and-builds) Fix missing Go tools, denied grants, stale lockfiles, and plugin build failures.