plugins 2.0 update

This commit is contained in:
KingKDot
2026-06-22 10:52:27 -05:00
parent e1f5e4c800
commit 30dfdda3ed
55 changed files with 2534 additions and 128 deletions
+263 -66
View File
@@ -1,10 +1,92 @@
# Overlord Plugins
This document explains how to build Overlord plugins using the **native plugin system**. Plugins run as native shared libraries (`.so` on Linux, `.dylib` on macOS, in-memory DLL on Windows), giving them full access to system APIs.
This document explains how to build Overlord plugins. **Plugin 2.0** uses WebAssembly modules for agent-side code and permissioned host bridges. The legacy native plugin system still works, but native plugins are now considered v1.
Plugins can be written in **any language** that can produce a C-ABI shared library: **Go**, **C**, **C++**, **Rust**, or anything else that compiles to native code.
Plugin UI and server-side logic can be written in JavaScript or TypeScript. Agent-side Plugin 2.0 code is a single WASM module that can be built from C, Rust, Zig, TinyGo, AssemblyScript, or any other toolchain that can target WASI-style WebAssembly. Legacy v1 agent plugins can still be written as native shared libraries.
> TL;DR: A plugin is a zip with platform-specific binaries (`.so`/`.dll`/`.dylib`) plus `<id>.html`, `<id>.css`, `<id>.js`. Upload it in the Plugins page or drop it in Overlord-Server/plugins. Optionally include a `server.js` for a per-plugin server runtime with a private SQLite DB, an RPC API, and live broadcasts to open UIs (see [section 11](#11-server-side-plugin-runtime)).
> TL;DR: A Plugin 2.0 bundle is a zip with `config.json`, `<id>.html`, `<id>.css`, and either `<id>.js` or TypeScript under `src/`. If it needs agent-side code, include one `.wasm` module. Upload it in the Plugins page or drop it in `Overlord-Server/plugins`. The server shows declared `needs` before a WASM plugin can be sent to a client.
## Plugin 2.0: WASM runtime
WASM plugins run inside the agent through a sandboxed runtime. They cannot access files directly; instead they declare broad file needs in `config.json`, and the agent exposes only those approved bridge operations.
```json
{
"name": "My WASM Plugin",
"version": "1.0.0",
"apiVersion": 2,
"runtime": "wasm",
"wasm": "my-plugin.wasm",
"needs": {
"files": [
{ "bucket": "pluginData", "access": ["read", "write", "list", "mkdir"], "reason": "Store plugin state" },
{ "bucket": "downloads", "access": ["list"], "reason": "Let the user pick downloaded files" }
]
}
}
```
Supported file buckets are `home`, `desktop`, `documents`, `downloads`, `temp`, `appData`, `pluginData`, and `fullDisk`. Supported operations are `read`, `write`, `list`, `delete`, and `mkdir`. Approval is tracked by a stable hash of the normalized needs; changing needs requires approval again.
Required exports:
| Export | Signature |
|--------|-----------|
| `overlord_alloc` | `ptr(uint32 size)` |
| `overlord_free` | `void(ptr, uint32 size)` |
| `overlord_on_load` | `int32(ptr hostInfo, uint32 hostInfoLen)` |
| `overlord_on_event` | `int32(ptr event, uint32 eventLen, ptr payload, uint32 payloadLen)` |
| `overlord_on_unload` | `void()` |
Host imports are available from both `env` and `overlord` modules:
| Import | Behavior |
|--------|----------|
| `overlord_emit(event, eventLen, payload, payloadLen)` | Sends an event back through the normal plugin event channel. |
| `overlord_host_info(out, outLen)` | Writes HostInfo JSON into `out`; includes `clientId`, `os`, `arch`, and `version`. |
| `overlord_fs_stat(bucket, bucketLen, path, pathLen, out, outLen)` | Writes JSON file metadata into `out`. |
| `overlord_fs_list(bucket, bucketLen, path, pathLen, out, outLen)` | Writes a JSON directory listing into `out`. |
| `overlord_fs_read(bucket, bucketLen, path, pathLen, out, outLen)` | Writes file bytes into `out`, max 32 MB. |
| `overlord_fs_write(bucket, bucketLen, path, pathLen, data, dataLen)` | Writes bytes to a bucket-relative path. |
| `overlord_fs_delete(bucket, bucketLen, path, pathLen)` | Deletes a bucket-relative file or directory. |
| `overlord_fs_mkdir(bucket, bucketLen, path, pathLen)` | Creates a bucket-relative directory. |
Bridge functions return non-negative byte counts or `0` on success. Negative return codes mean denied, invalid path/memory, not found, output buffer too small, file too large, or I/O failure.
See `plugins/sample-wasm` for a C/WASI example, `plugins/sample-wasm-hostinfo` for a TinyGo example, and `plugins/sample-wasm-platform-note` for a Rust example.
## TypeScript UI and server logic
Plugin bundles can ship TypeScript source for browser UI logic and the optional server runtime. The server compiles these files during extraction, so the uploaded zip can stay clean and source-oriented.
Default layout:
```
sample-ts-fullstack.zip
├─ config.json
├─ sample-ts-fullstack.html
├─ sample-ts-fullstack.css
└─ src/
├─ ui.ts
├─ server.ts
└─ shared.ts
```
`src/ui.ts` is compiled to `assets/<pluginId>.js`. `src/server.ts` is compiled to `server.js`. Both entrypoints can import other local files, so plugin authors can split code across multiple TypeScript modules instead of maintaining one large JavaScript file. This is only for browser UI and server-side plugin runtime logic; agent-side WASM is still supplied as a prebuilt `.wasm` file.
You can override entrypoints in `config.json`:
```json
{
"apiVersion": 2,
"uiEntry": "src/browser/main.ts",
"serverEntry": "src/backend/index.ts"
}
```
Only files under `src/` are copied for compilation. Extraction does not run `npm install`, download packages, or execute arbitrary build scripts; use relative imports and APIs already available in the browser or the Overlord plugin server runtime.
See `plugins/sample-ts-fullstack` for a multi-file TypeScript UI/backend example.
## 1) How plugins are structured
@@ -16,47 +98,84 @@ A plugin bundle is a zip file named after the plugin ID:
<pluginId>.zip
```
Inside the zip (root level), you need:
- **Platform-specific binaries** named `<pluginId>-<os>-<arch>.<ext>`
- **Web assets**: `<pluginId>.html`, `<pluginId>.css`, `<pluginId>.js`
Example for plugin ID `sample`:
For a Plugin 2.0 source-oriented bundle, the root normally contains:
```
sample.zip
├─ sample-linux-amd64.so
├─ sample-linux-arm64.so
├─ sample-darwin-arm64.dylib
├─ sample-windows-amd64.dll
├─ sample.html
├─ sample.css
├─ sample.js
├─ server.js (optional — server-side runtime, see section 11)
└─ config.json (optional — enables navbar & metadata)
<pluginId>.zip
├─ config.json
├─ <pluginId>.html
├─ <pluginId>.css
├─ <pluginId>.js (optional when src/ui.ts exists)
├─ <pluginId>.wasm (optional agent-side WASM module)
└─ src/ (optional TypeScript/JavaScript source)
├─ ui.ts (compiled to assets/<pluginId>.js)
├─ server.ts (compiled to server.js)
└─ shared.ts
```
For a legacy native v1 bundle, include platform-specific binaries named `<pluginId>-<os>-<arch>.<ext>` plus web assets.
Plugin 2.0 example for plugin ID `sample-wasm`:
```
sample-wasm.zip
├─ config.json
├─ sample-wasm.html
├─ sample-wasm.css
├─ sample-wasm.wasm
└─ src/
├─ ui.ts
└─ server.ts
```
When the server extracts the zip:
```
Overlord-Server/plugins/sample/
├─ sample-linux-amd64.so
├─ sample-linux-arm64.so
├─ sample-darwin-arm64.dylib
├─ sample-windows-amd64.dll
├─ server.js (optional — picked up by the plugin runtime)
Overlord-Server/plugins/sample-wasm/
├─ sample-wasm.wasm
├─ server.js (compiled from src/server.ts when present)
├─ manifest.json (auto-generated, merged with config.json)
├─ src/ (copied source files)
├─ data/
│ └─ plugin.db (auto-created when server.js is present)
└─ assets/
├─ sample.html
├─ sample.css
└─ sample.js
├─ sample-wasm.html
├─ sample-wasm.css
└─ sample-wasm.js (compiled from src/ui.ts or copied from root JS)
```
### Architecture validation
### Runtime selection
The server matches binaries to clients by OS and architecture. Binary filenames **must** follow the naming convention `<pluginId>-<os>-<arch>.<ext>`:
`config.json` controls the runtime style:
```json
{
"apiVersion": 2,
"runtime": "wasm",
"wasm": "sample-wasm.wasm"
}
```
Use `runtime: "wasm"` when the plugin has an agent-side WASM module. Use `runtime: "server"` for UI/server-only Plugin 2.0 bundles. Legacy native bundles omit `apiVersion`/`runtime` or use `runtime: "native"`.
### WASM architecture behavior
WASM plugins are universal: the same `.wasm` file is sent to Windows, Linux, and macOS clients on any supported architecture. To branch by client platform, read HostInfo either from `overlord_on_load(hostInfo, hostInfoLen)` or by calling `overlord_host_info(out, outLen)`.
Example HostInfo:
```json
{
"clientId": "abc123",
"os": "windows",
"arch": "amd64",
"version": "1.0.0"
}
```
### Legacy native architecture validation
Legacy native v1 binaries are still matched to clients by OS and architecture. Binary filenames **must** follow the naming convention `<pluginId>-<os>-<arch>.<ext>`:
| OS | Arch | Example filename |
|----------|---------|------------------------------|
@@ -67,7 +186,7 @@ The server matches binaries to clients by OS and architecture. Binary filenames
| darwin | amd64 | `sample-darwin-amd64.dylib` |
| darwin | arm64 | `sample-darwin-arm64.dylib` |
The server will **never** send an x64 binary to an ARM client (or vice versa). If no binary matches the client's platform, loading is skipped with an error.
The server will **never** send an x64 native binary to an ARM client (or vice versa). If no native binary matches the client's platform, loading is skipped with an error.
### Manifest fields
@@ -77,13 +196,18 @@ The auto-generated manifest (merged with `config.json` if present):
{
"id": "sample",
"name": "Sample Plugin",
"apiVersion": 2,
"runtime": "wasm",
"version": "1.0.0",
"description": "An example plugin",
"wasm": "sample.wasm",
"needs": {
"files": [
{ "bucket": "pluginData", "access": ["read", "write"], "reason": "Store plugin state" }
]
},
"binaries": {
"linux-amd64": "sample-linux-amd64.so",
"linux-arm64": "sample-linux-arm64.so",
"darwin-arm64": "sample-darwin-arm64.dylib",
"windows-amd64": "sample-windows-amd64.dll"
"wasm32-wasi": "sample.wasm"
},
"entry": "sample.html",
"assets": {
@@ -98,7 +222,7 @@ The auto-generated manifest (merged with `config.json` if present):
}
```
The `navbar` field is only present when a `config.json` is included in the bundle.
The `navbar`, `needs`, `wasm`, and TypeScript entrypoint fields are present only when declared or inferred from the bundle.
### Global Nav Bar Plugins (`config.json`)
@@ -125,9 +249,11 @@ When the server extracts the bundle:
> **Important:** `config.json` must be in the **root** of the zip (not inside a subfolder). The build scripts automatically include it if it exists at the plugin source root. The manifest is re-generated on every extraction (triggered when the zip is newer than `manifest.json`), so keep `config.json` in the zip to avoid losing the navbar registration on re-upload.
## 2) Plugin ABI (all languages)
## 2) Legacy native plugin ABI
Every plugin — regardless of language — must export **C-callable functions** with specific signatures. The ABI differs slightly between Windows and Unix.
This section applies only to legacy v1 native agent plugins. Plugin 2.0 WASM modules use the `overlord_*` ABI described above.
Every native plugin must export **C-callable functions** with specific signatures. The ABI differs slightly between Windows and Unix.
### Required exports
@@ -199,7 +325,18 @@ The `hostInfo` buffer passed to `PluginOnLoad` is JSON:
- **Linux** — Shared libraries are loaded in memory via `memfd_create` + `dlopen` on `/proc/self/fd/`. No files touch disk.
- **macOS** — Shared libraries are written to a temp file, `dlopen`'d, then the temp file is deleted.
## 3) Sample plugins by language
## 3) Sample plugins
Current Plugin 2.0 samples:
| Sample | Purpose |
|--------|---------|
| `sample-wasm` | C/WASI file bridge sample using `pluginData`, `downloads`, and `overlord_host_info`. |
| `sample-wasm-hostinfo` | TinyGo sample that queries HostInfo from a universal WASM module. |
| `sample-wasm-platform-note` | Rust sample that branches by `os`/`arch` inside one WASM module and writes a platform-specific note. |
| `sample-ts-fullstack` | TypeScript UI plus TypeScript server runtime with shared local modules. |
Legacy native samples remain available:
### Go (`sample-go/`)
@@ -390,18 +527,20 @@ cargo build --release --target=x86_64-pc-windows-msvc
cargo build --release --target=aarch64-unknown-linux-gnu
```
## 4) Build scripts & cross-compilation
## 4) Legacy native build scripts & cross-compilation
Each language has `.bat` (Windows) and `.sh` (Unix) build scripts. All scripts support the `BUILD_TARGETS` environment variable to compile for multiple platforms in one invocation.
This section applies to legacy native v1 plugins. Plugin 2.0 WASM modules are universal and do not need one binary per OS/architecture, though you still need a WASM toolchain such as WASI clang, Rust `wasm32-wasip1`, Zig, TinyGo, or AssemblyScript.
Each legacy native sample keeps its `.bat` (Windows) and `.sh` (Unix) build scripts in the plugin's own directory. All scripts support the `BUILD_TARGETS` environment variable to compile for multiple platforms in one invocation.
### Available build scripts
| Language | Windows | Unix |
|----------|--------------------------|-------------------------|
| Go | `build-plugin.bat` | `build-plugin.sh` |
| C | `build-plugin-c.bat` | `build-plugin-c.sh` |
| C++ | `build-plugin-cpp.bat` | `build-plugin-cpp.sh` |
| Rust | `build-plugin-rust.bat` | `build-plugin-rust.sh` |
| Go | `sample-go/build.bat` | `sample-go/build.sh` |
| C | `sample-c/build.bat` | `sample-c/build.sh` |
| C++ | `sample-cpp/build.bat` | `sample-cpp/build.sh` |
| Rust | `sample-rust/build.bat` | `sample-rust/build.sh` |
### Usage
@@ -409,25 +548,26 @@ All scripts default to building for the host platform only:
```bash
# Build for current platform
./build-plugin-c.sh
cd sample-c
./build.sh
# Build for multiple targets
BUILD_TARGETS="linux-amd64 linux-arm64 windows-amd64" ./build-plugin-c.sh
BUILD_TARGETS="linux-amd64 linux-arm64 windows-amd64" ./build.sh
# Custom plugin directory
./build-plugin-c.sh /path/to/my-plugin
./build.sh /path/to/my-plugin
```
```bat
REM Build for current platform
build-plugin-c.bat
sample-c\build.bat
REM Build for multiple targets
set BUILD_TARGETS=windows-amd64 windows-arm64
build-plugin-c.bat
sample-c\build.bat
REM Custom plugin directory
build-plugin-c.bat C:\path\to\my-plugin
sample-c\build.bat C:\path\to\my-plugin
```
### Cross-compilation
@@ -460,8 +600,8 @@ On Windows `.bat` scripts, MSVC (`cl`) is tried first with the appropriate `/lin
On Unix `.sh` scripts, override the compiler with `CC=<compiler>` (C) or `CXX=<compiler>` (C++):
```bash
CC=zig-cc BUILD_TARGETS="linux-arm64" ./build-plugin-c.sh
CXX=zig-c++ BUILD_TARGETS="linux-arm64" ./build-plugin-cpp.sh
CC=zig-cc BUILD_TARGETS="linux-arm64" ./sample-c/build.sh
CXX=zig-c++ BUILD_TARGETS="linux-arm64" ./sample-cpp/build.sh
```
### Installing cross-compiler toolchains
@@ -487,6 +627,50 @@ brew install FiloSottile/musl-cross/musl-cross
rustup target add aarch64-apple-darwin x86_64-apple-darwin
```
### WASM build examples
Plugin 2.0 samples keep their Windows builders in their own plugin directories:
| Script | Purpose |
|--------|---------|
| `sample-wasm/build.bat` | Builds and packages `sample-wasm`. |
| `sample-wasm-hostinfo/build.bat` | Builds and packages `sample-wasm-hostinfo`. |
| `sample-wasm-platform-note/build.bat` | Builds and packages `sample-wasm-platform-note`. |
| `sample-ts-fullstack/build.bat` | Packages the TypeScript UI/server sample; the server compiles TypeScript during extraction. |
Usage:
```bat
REM Per-sample Plugin 2.0 build
sample-ts-fullstack\build.bat
sample-wasm\build.bat
```
The sample WASM plugins intentionally use different source languages:
| Sample | Source language | Toolchain |
|--------|-----------------|-----------|
| `sample-wasm` | C | WASI-capable `clang` |
| `sample-wasm-hostinfo` | Go | TinyGo 0.41.0+ with `-target=wasi` |
| `sample-wasm-platform-note` | Rust | Rust target `wasm32-wasip1` |
A minimal manual C/WASI build for `sample-wasm` looks like:
```bash
clang --target=wasm32-wasi -O2 \
-Wl,--no-entry \
-Wl,--export=overlord_alloc \
-Wl,--export=overlord_free \
-Wl,--export=overlord_on_load \
-Wl,--export=overlord_on_event \
-Wl,--export=overlord_on_unload \
-o sample-wasm.wasm native/sample_wasm.c
```
The generated `.wasm` goes at the root of the plugin zip and is referenced by `config.json`.
For the TinyGo sample, install TinyGo 0.41.0 or newer and run `sample-wasm-hostinfo\build.bat`. For the Rust sample, install the target with `rustup target add wasm32-wasip1`, then run `sample-wasm-platform-note\build.bat`.
## 5) Install & open a plugin
### Install / upload
@@ -508,7 +692,7 @@ For **global nav bar plugins** (those registered via `config.json`), the UI open
/plugins/<pluginId>
```
The server reads your `<pluginId>.html`, extracts the body content, and renders it inside the standard Overlord layout. Your CSS and JS are loaded from `/plugins/<pluginId>/assets/`.
The server reads your `<pluginId>.html`, extracts the body content, and renders it inside the standard Overlord layout. Your CSS and generated/copied JS are loaded from `/plugins/<pluginId>/assets/`.
To get the `clientId` in your JS (for per-client plugins):
@@ -529,7 +713,9 @@ const onlineIds = items.filter(c => c.online).map(c => c.id);
Overlord plugins have **two parts**:
1. **UI (HTML/CSS/JS)** — Runs in the browser, calls server APIs.
2. **Native module** — Runs in the agent (client) process as a loaded shared library.
2. **Optional agent module** — Plugin 2.0 uses WASM; legacy v1 uses native shared libraries.
Plugins can also include optional **server-side logic** through `server.js` or compiled `src/server.ts`. That code runs in the server plugin worker and exposes RPC/broadcast APIs to the UI.
### UI → agent (plugin event)
@@ -545,13 +731,13 @@ POST /api/clients/<clientId>/plugins/<pluginId>/event
If the plugin is not loaded yet, the server will load it on the client, queue the event, and deliver it once ready.
### Agent → plugin (direct function call)
### Agent → plugin
The agent calls your `OnEvent(event, payload)` function directly with JSON-encoded data. No stdin/stdout pipes, no msgpack — just a direct function call.
For WASM plugins, the agent calls `overlord_on_event(eventPtr, eventLen, payloadPtr, payloadLen)`. For legacy native plugins, the agent calls `PluginOnEvent(event, payload)`. In both cases the payload is JSON-encoded data from the UI/server.
### Plugin → agent (callback)
### Plugin → agent/server events
Your plugin sends events back to the host using the callback received during `OnLoad`:
WASM plugins send events with `overlord_emit(event, eventLen, payload, payloadLen)`. Legacy native plugins use the callback received during `PluginOnLoad`.
**Go:**
```go
@@ -582,7 +768,16 @@ The agent sends these events to the server:
## 7) What can plugins do?
Since plugins run as native code, they can:
WASM Plugin 2.0 agent modules are sandboxed. They can:
- Receive UI/server events.
- Send events back through `overlord_emit`.
- Read HostInfo (`clientId`, `os`, `arch`, `version`).
- Use declared file bridges after the user approves the plugin's `needs`.
WASM modules cannot directly access arbitrary files, processes, network sockets, or OS APIs unless Overlord exposes an explicit host bridge.
Legacy native v1 plugins run as native code and can:
- Call any system API (file I/O, network, processes, etc.)
- Use any library available to their language
@@ -590,7 +785,7 @@ Since plugins run as native code, they can:
- Access hardware
- Do anything a normal native program can do
Plugins have the same capabilities as the agent itself.
Legacy native plugins have the same capabilities as the agent itself.
| Language | Can be fully unloaded? | Runtime overhead |
|----------|----------------------|------------------|
@@ -647,9 +842,10 @@ If you want defensive scoping anyway, wrap your plugin JS in an IIFE so top-leve
### Plugin management
- `GET /api/plugins` — list installed plugins (includes `autoLoad` and `autoStartEvents` per plugin)
- `GET /api/plugins` — list installed plugins, including `runtime`, `apiVersion`, `needs`, `needsHash`, `needsApproved`, `autoLoad`, and `autoStartEvents`
- `POST /api/plugins/upload` — upload zip
- `POST /api/plugins/<id>/enable` — enable/disable
- `POST /api/plugins/<id>/needs/approve` — approve the currently declared Plugin 2.0 needs hash
- `POST /api/plugins/<id>/autoload` — configure auto-load on client connect
- `DELETE /api/plugins/<id>` — remove (preserves `data/` directory)
@@ -775,10 +971,11 @@ Content-Type: application/json
### Notes
- Auto-load respects the `enabled` flag — disabled plugins are never auto-loaded
- Auto-load for plugins with declared `needs` is blocked until those needs are approved
- Auto-load state is persisted in `.plugin-state.json` and survives server restarts
- Deleting a plugin also removes its auto-load configuration
- The server selects the correct binary for each client's OS/architecture automatically
- If a plugin binary isn't available for a client's platform, the auto-load silently skips that client
- WASM plugins use one universal module for every OS/architecture
- Legacy native plugins still require a compatible binary for each target platform; if one is unavailable, auto-load skips that client
## 10) Server-side plugin data directory
@@ -1197,11 +1394,11 @@ Set the `PLUGIN_SIGN_KEY` environment variable to automatically sign plugins dur
```bash
# Unix
PLUGIN_SIGN_KEY=path/to/my-signing-key.key ./build-plugin.sh
PLUGIN_SIGN_KEY=path/to/my-signing-key.key ./sample-go/build.sh
# Windows
set PLUGIN_SIGN_KEY=path\to\my-signing-key.key
build-plugin.bat
sample-go\build.bat
```
### How Signing Works
@@ -1,8 +1,7 @@
@echo off
setlocal enabledelayedexpansion
set "ROOT=%~dp0"
set "PLUGIN_DIR=%ROOT%sample-c"
set "PLUGIN_DIR=%~dp0."
if not "%~1"=="" set "PLUGIN_DIR=%~1"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
@@ -2,7 +2,7 @@
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="${1:-${ROOT_DIR}/sample-c}"
PLUGIN_DIR="${1:-${ROOT_DIR}}"
NATIVE_DIR="${PLUGIN_DIR}/native"
PLUGIN_NAME="sample-c"
ZIP_OUT="${PLUGIN_DIR}/${PLUGIN_NAME}.zip"
@@ -1,8 +1,7 @@
@echo off
setlocal enabledelayedexpansion
set "ROOT=%~dp0"
set "PLUGIN_DIR=%ROOT%sample-cpp"
set "PLUGIN_DIR=%~dp0."
if not "%~1"=="" set "PLUGIN_DIR=%~1"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
@@ -2,7 +2,7 @@
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="${1:-${ROOT_DIR}/sample-cpp}"
PLUGIN_DIR="${1:-${ROOT_DIR}}"
NATIVE_DIR="${PLUGIN_DIR}/native"
PLUGIN_NAME="sample-cpp"
ZIP_OUT="${PLUGIN_DIR}/${PLUGIN_NAME}.zip"
+4 -3
View File
@@ -16,13 +16,14 @@ Use the provided build scripts:
```bash
# Linux/macOS
./build-plugin.sh
cd sample-go
./build.sh
# Multiple targets
BUILD_TARGETS="linux-amd64 linux-arm64 darwin-arm64" ./build-plugin.sh
BUILD_TARGETS="linux-amd64 linux-arm64 darwin-arm64" ./build.sh
# Windows
build-plugin.bat
sample-go\build.bat
```
## Create the zip
@@ -1,8 +1,7 @@
@echo off
setlocal enabledelayedexpansion
set "ROOT=%~dp0"
set "PLUGIN_DIR=%ROOT%sample-go"
set "PLUGIN_DIR=%~dp0."
if not "%~1"=="" set "PLUGIN_DIR=%~1"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
@@ -92,7 +91,7 @@ if defined PLUGIN_SIGN_KEY (
where bun >nul 2>&1
if not errorlevel 1 (
echo [sign] Signing plugin with key: %PLUGIN_SIGN_KEY%
bun run "%ROOT%Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
bun run "%~dp0..\..\Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
) else (
echo [warn] bun not found, skipping plugin signing
)
@@ -2,7 +2,7 @@
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="${1:-${ROOT_DIR}/sample-go}"
PLUGIN_DIR="${1:-${ROOT_DIR}}"
NATIVE_DIR="${PLUGIN_DIR}/native"
PLUGIN_NAME="sample"
ZIP_OUT="${PLUGIN_DIR}/${PLUGIN_NAME}.zip"
@@ -69,10 +69,9 @@ fi
# Optional: sign the plugin if PLUGIN_SIGN_KEY is set
if [[ -n "${PLUGIN_SIGN_KEY:-}" ]]; then
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if command -v bun >/dev/null 2>&1; then
echo "[sign] Signing plugin with key: ${PLUGIN_SIGN_KEY}"
bun run "${SCRIPT_DIR}/Overlord-Server/scripts/plugin-sign.ts" --key "${PLUGIN_SIGN_KEY}" "${ZIP_OUT}"
bun run "${ROOT_DIR}/../../Overlord-Server/scripts/plugin-sign.ts" --key "${PLUGIN_SIGN_KEY}" "${ZIP_OUT}"
else
echo "[warn] bun not found, skipping plugin signing" >&2
fi
@@ -1,8 +1,7 @@
@echo off
setlocal enabledelayedexpansion
set "ROOT=%~dp0"
set "PLUGIN_DIR=%ROOT%sample-rust"
set "PLUGIN_DIR=%~dp0."
if not "%~1"=="" set "PLUGIN_DIR=%~1"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
@@ -2,7 +2,7 @@
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="${1:-${ROOT_DIR}/sample-rust}"
PLUGIN_DIR="${1:-${ROOT_DIR}}"
NATIVE_DIR="${PLUGIN_DIR}/native"
PLUGIN_NAME="sample-rust"
ZIP_OUT="${PLUGIN_DIR}/${PLUGIN_NAME}.zip"
+9
View File
@@ -0,0 +1,9 @@
# Sample TS Fullstack Plugin
This sample intentionally ships TypeScript source instead of generated JavaScript.
The server extracts the bundle, compiles `src/ui.ts` to `assets/sample-ts-fullstack.js`, and compiles `src/server.ts` to `server.js`. Both entrypoints import `src/shared.ts`, demonstrating that plugin authors can split logic across multiple TypeScript files.
No package install is performed during plugin extraction; use relative imports or APIs already available in the browser/server runtime.
On Windows, run this sample's local `build.bat` to create `sample-ts-fullstack.zip`. The batch file packages the TypeScript sources cleanly; compilation still happens on the server during extraction.
+60
View File
@@ -0,0 +1,60 @@
@echo off
setlocal enabledelayedexpansion
set "PLUGIN_DIR=%~dp0"
set "PLUGIN_NAME=sample-ts-fullstack"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
set "WASM_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.wasm"
set "ZIP_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.zip"
if not exist "%PLUGIN_DIR%\config.json" (
echo [error] config.json not found in %PLUGIN_DIR%
exit /b 1
)
set "WASM_SOURCE="
if exist "%NATIVE_DIR%" (
for %%S in ("%NATIVE_DIR%\*.c") do (
if not defined WASM_SOURCE set "WASM_SOURCE=%%~fS"
)
)
if defined WASM_SOURCE (
where clang >nul 2>&1
if errorlevel 1 (
echo [error] clang was not found. Install a WASI-capable clang or provide %WASM_OUT% yourself.
exit /b 1
)
echo [build] clang --target=wasm32-wasi -O2 "!WASM_SOURCE!" ^> "%WASM_OUT%"
clang --target=wasm32-wasi -O2 -Wl,--no-entry -Wl,--allow-undefined -Wl,--export=overlord_alloc -Wl,--export=overlord_free -Wl,--export=overlord_on_load -Wl,--export=overlord_on_event -Wl,--export=overlord_on_unload -o "%WASM_OUT%" "!WASM_SOURCE!"
if errorlevel 1 (
echo [error] WASM build failed
exit /b 1
)
)
if exist "%ZIP_OUT%" del /f /q "%ZIP_OUT%"
pushd "%PLUGIN_DIR%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$zip = '%ZIP_OUT%'; $items = @(); foreach ($file in @('config.json', '%PLUGIN_NAME%.html', '%PLUGIN_NAME%.css', '%PLUGIN_NAME%.js', '%PLUGIN_NAME%.wasm', 'server.js')) { if (Test-Path -LiteralPath $file -PathType Leaf) { $items += $file } }; foreach ($dir in @('src', 'assets')) { if (Test-Path -LiteralPath $dir -PathType Container) { $items += $dir } }; if ($items.Count -eq 0) { throw 'No plugin files found to package' }; Compress-Archive -Path $items -DestinationPath $zip -Force"
set "ZIP_STATUS=%ERRORLEVEL%"
popd
if not "%ZIP_STATUS%"=="0" exit /b %ZIP_STATUS%
if errorlevel 1 (
echo [error] zip failed
exit /b 1
)
if defined PLUGIN_SIGN_KEY (
where bun >nul 2>&1
if not errorlevel 1 (
echo [sign] Signing plugin with key: %PLUGIN_SIGN_KEY%
bun run "%~dp0..\..\Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
) else (
echo [warn] bun not found, skipping plugin signing
)
)
echo [ok] %ZIP_OUT%
@@ -0,0 +1,3 @@
#sample-ts-output {
min-height: 9rem;
}
@@ -0,0 +1,11 @@
<div class="space-y-3">
<div>
<h2 class="text-lg font-semibold text-slate-100">Sample TS Fullstack</h2>
<p class="text-sm text-slate-400">Multiple TypeScript files compiled by the server at plugin extraction time.</p>
</div>
<div class="flex gap-2">
<button id="sample-ts-ping" class="px-3 py-2 rounded-lg border border-cyan-700 bg-cyan-950/40 text-cyan-100">Ping backend</button>
<button id="sample-ts-count" class="px-3 py-2 rounded-lg border border-emerald-700 bg-emerald-950/40 text-emerald-100">Increment</button>
</div>
<pre id="sample-ts-output" class="text-xs text-slate-300 whitespace-pre-wrap"></pre>
</div>
+41
View File
@@ -0,0 +1,41 @@
import type { RpcResponse } from "./shared";
type PluginContext = {
db: {
exec(sql: string): void;
prepare(sql: string): {
get(...args: unknown[]): any;
run(...args: unknown[]): any;
};
};
log: { info(message: string): void };
};
function now(): string {
return new Date().toISOString();
}
function response(message: string, count?: number): RpcResponse {
return { message, count, at: now() };
}
export default {
setup(ctx: PluginContext) {
ctx.db.exec("CREATE TABLE IF NOT EXISTS counter (id INTEGER PRIMARY KEY CHECK (id = 1), value INTEGER NOT NULL)");
ctx.db.prepare("INSERT OR IGNORE INTO counter (id, value) VALUES (1, 0)").run();
ctx.log.info("sample-ts-fullstack ready");
},
rpc: {
ping(): RpcResponse {
return response("hello from TypeScript server");
},
increment(ctx: PluginContext, params: unknown): RpcResponse {
const by = typeof (params as any)?.by === "number" ? Math.trunc((params as any).by) : 1;
ctx.db.prepare("UPDATE counter SET value = value + ? WHERE id = 1").run(by);
const row = ctx.db.prepare("SELECT value FROM counter WHERE id = 1").get();
return response("counter updated", Number(row?.value || 0));
},
},
};
+10
View File
@@ -0,0 +1,10 @@
export type RpcResponse = {
message: string;
count?: number;
at: string;
};
export function formatLine(label: string, value: RpcResponse): string {
const count = typeof value.count === "number" ? ` count=${value.count}` : "";
return `${label}: ${value.message}${count} at ${value.at}`;
}
+39
View File
@@ -0,0 +1,39 @@
import { formatLine, type RpcResponse } from "./shared";
const output = document.getElementById("sample-ts-output");
const pingButton = document.getElementById("sample-ts-ping");
const countButton = document.getElementById("sample-ts-count");
function append(message: string) {
if (!output) return;
output.textContent = `${message}\n${output.textContent || ""}`;
}
async function rpc(method: string, params?: unknown): Promise<RpcResponse> {
const res = await fetch("/api/plugins/sample-ts-fullstack/rpc", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ method, params }),
});
const body = await res.json();
if (!res.ok || body.ok === false) {
throw new Error(body.error || res.statusText);
}
return body.result as RpcResponse;
}
pingButton?.addEventListener("click", async () => {
try {
append(formatLine("ping", await rpc("ping")));
} catch (err) {
append(`ping failed: ${err instanceof Error ? err.message : String(err)}`);
}
});
countButton?.addEventListener("click", async () => {
try {
append(formatLine("increment", await rpc("increment", { by: 1 })));
} catch (err) {
append(`increment failed: ${err instanceof Error ? err.message : String(err)}`);
}
});
+5
View File
@@ -0,0 +1,5 @@
# Sample WASM HostInfo Plugin
This Plugin 2.0 sample is written in Go for TinyGo. It demonstrates how a universal WASM module can read HostInfo and emit it back to the UI.
On Windows, install TinyGo 0.41.0 or newer, then run this sample's local `build.bat`. TinyGo 0.41.0 added Go 1.26 support. The builder runs `tinygo build -target=wasi`, writes `sample-wasm-hostinfo.wasm`, and creates `sample-wasm-hostinfo.zip`.
+55
View File
@@ -0,0 +1,55 @@
@echo off
setlocal enabledelayedexpansion
set "PLUGIN_DIR=%~dp0"
set "PLUGIN_NAME=sample-wasm-hostinfo"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
set "WASM_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.wasm"
set "ZIP_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.zip"
if not exist "%PLUGIN_DIR%\config.json" (
echo [error] config.json not found in %PLUGIN_DIR%
exit /b 1
)
set "WASM_SOURCE=%NATIVE_DIR%\main.go"
if exist "%WASM_SOURCE%" (
where tinygo >nul 2>&1
if errorlevel 1 (
echo [error] tinygo was not found. Install TinyGo or provide %WASM_OUT% yourself.
exit /b 1
)
echo [build] tinygo build -target=wasi -opt=2 -no-debug -o "%WASM_OUT%" "%WASM_SOURCE%"
tinygo build -target=wasi -opt=2 -no-debug -o "%WASM_OUT%" "%WASM_SOURCE%"
if errorlevel 1 (
echo [error] WASM build failed
exit /b 1
)
)
if exist "%ZIP_OUT%" del /f /q "%ZIP_OUT%"
pushd "%PLUGIN_DIR%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$zip = '%ZIP_OUT%'; $items = @(); foreach ($file in @('config.json', '%PLUGIN_NAME%.html', '%PLUGIN_NAME%.css', '%PLUGIN_NAME%.js', '%PLUGIN_NAME%.wasm', 'server.js')) { if (Test-Path -LiteralPath $file -PathType Leaf) { $items += $file } }; foreach ($dir in @('src', 'assets')) { if (Test-Path -LiteralPath $dir -PathType Container) { $items += $dir } }; if ($items.Count -eq 0) { throw 'No plugin files found to package' }; Compress-Archive -Path $items -DestinationPath $zip -Force"
set "ZIP_STATUS=%ERRORLEVEL%"
popd
if not "%ZIP_STATUS%"=="0" exit /b %ZIP_STATUS%
if errorlevel 1 (
echo [error] zip failed
exit /b 1
)
if defined PLUGIN_SIGN_KEY (
where bun >nul 2>&1
if not errorlevel 1 (
echo [sign] Signing plugin with key: %PLUGIN_SIGN_KEY%
bun run "%~dp0..\..\Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
) else (
echo [warn] bun not found, skipping plugin signing
)
)
echo [ok] %ZIP_OUT%
@@ -0,0 +1,93 @@
package main
import "unsafe"
//go:wasmimport env overlord_emit
func overlordEmit(eventPtr, eventLen, payloadPtr, payloadLen uint32) int32
//go:wasmimport env overlord_host_info
func overlordHostInfo(outPtr, outLen uint32) int32
var heap = make([]byte, 64*1024)
var heapOffset uint32 = 8
var hostInfo [1024]byte
var hostInfoLen uint32
//go:export overlord_alloc
func overlordAlloc(size uint32) uint32 {
if size == 0 {
size = 1
}
ptr := (heapOffset + 7) &^ 7
next := ptr + size
if next >= uint32(len(heap)) {
return 0
}
heapOffset = next
return uint32(uintptr(unsafe.Pointer(&heap[ptr])))
}
//go:export overlord_free
func overlordFree(ptr, size uint32) {
_, _ = ptr, size
}
//go:export overlord_on_load
func overlordOnLoad(hostPtr, hostLen uint32) int32 {
n := hostLen
if n > uint32(len(hostInfo)) {
n = uint32(len(hostInfo))
}
copy(hostInfo[:n], bytesAt(hostPtr, n))
hostInfoLen = n
emit("ready", hostInfo[:hostInfoLen])
return 0
}
//go:export overlord_on_event
func overlordOnEvent(eventPtr, eventLen, payloadPtr, payloadLen uint32) int32 {
_, _ = payloadPtr, payloadLen
event := string(bytesAt(eventPtr, eventLen))
if event != "query_host" {
return 0
}
var buf [1024]byte
n := overlordHostInfo(uint32(uintptr(unsafe.Pointer(&buf[0]))), uint32(len(buf)))
if n < 0 {
emitString("host_info", `{"error":"host info buffer too small"}`)
return 0
}
emit("host_info", buf[:uint32(n)])
return 0
}
//go:export overlord_on_unload
func overlordOnUnload() {}
func emitString(event string, payload string) {
emit(event, []byte(payload))
}
func emit(event string, payload []byte) {
eventBytes := []byte(event)
var eventPtr uint32
var payloadPtr uint32
if len(eventBytes) > 0 {
eventPtr = uint32(uintptr(unsafe.Pointer(&eventBytes[0])))
}
if len(payload) > 0 {
payloadPtr = uint32(uintptr(unsafe.Pointer(&payload[0])))
}
overlordEmit(eventPtr, uint32(len(eventBytes)), payloadPtr, uint32(len(payload)))
}
func bytesAt(ptr, length uint32) []byte {
if length == 0 {
return nil
}
return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(ptr))), length)
}
func main() {}
@@ -0,0 +1,22 @@
#sample-wasm-hostinfo-output {
min-height: 8rem;
}
.sample-wasm-hostinfo-field {
border: 1px solid rgba(8, 145, 178, 0.45);
background: rgba(8, 47, 73, 0.28);
padding: 0.75rem;
}
.sample-wasm-hostinfo-field span {
display: block;
color: rgb(148, 163, 184);
font-size: 0.75rem;
}
.sample-wasm-hostinfo-field strong {
display: block;
color: rgb(224, 242, 254);
font-size: 0.95rem;
overflow-wrap: anywhere;
}
@@ -0,0 +1,12 @@
<div class="space-y-3">
<h2 class="text-lg font-semibold text-slate-100">Sample WASM Host Info</h2>
<button id="sample-wasm-hostinfo-run" class="px-3 py-2 rounded-lg border border-cyan-700 bg-cyan-950/40 text-cyan-100">Query host info</button>
<div id="sample-wasm-hostinfo-status" class="text-xs text-slate-400">Waiting for host info</div>
<div class="grid gap-2 sm:grid-cols-2">
<div class="sample-wasm-hostinfo-field"><span>Client</span><strong id="sample-wasm-hostinfo-client">-</strong></div>
<div class="sample-wasm-hostinfo-field"><span>Version</span><strong id="sample-wasm-hostinfo-version">-</strong></div>
<div class="sample-wasm-hostinfo-field"><span>OS</span><strong id="sample-wasm-hostinfo-os">-</strong></div>
<div class="sample-wasm-hostinfo-field"><span>Arch</span><strong id="sample-wasm-hostinfo-arch">-</strong></div>
</div>
<pre id="sample-wasm-hostinfo-output" class="text-xs text-slate-300 whitespace-pre-wrap"></pre>
</div>
@@ -0,0 +1,93 @@
(() => {
const out = document.getElementById("sample-wasm-hostinfo-output");
const btn = document.getElementById("sample-wasm-hostinfo-run");
const status = document.getElementById("sample-wasm-hostinfo-status");
const fields = {
clientId: document.getElementById("sample-wasm-hostinfo-client"),
version: document.getElementById("sample-wasm-hostinfo-version"),
os: document.getElementById("sample-wasm-hostinfo-os"),
arch: document.getElementById("sample-wasm-hostinfo-arch"),
};
const clientId = new URLSearchParams(window.location.search).get("clientId");
const pluginId = "sample-wasm-hostinfo";
let polling = false;
function log(message) {
if (out) out.textContent = `${message}\n${out.textContent || ""}`;
}
function setStatus(message) {
if (status) status.textContent = message;
}
function parsePayload(payload) {
if (payload == null) return {};
if (typeof payload === "string") {
try { return JSON.parse(payload); } catch (_) { return { raw: payload }; }
}
return payload;
}
function renderHostInfo(payload) {
const info = parsePayload(payload);
if (info.error) {
setStatus(info.error);
log(JSON.stringify(info, null, 2));
return;
}
if (fields.clientId) fields.clientId.textContent = info.clientId || "-";
if (fields.version) fields.version.textContent = info.version || "-";
if (fields.os) fields.os.textContent = info.os || "-";
if (fields.arch) fields.arch.textContent = info.arch || "-";
setStatus("Host info received");
log(JSON.stringify(info, null, 2));
}
function handlePluginEvent(event, payload) {
if (event === "ready" || event === "host_info") renderHostInfo(payload);
}
window.addEventListener("message", (e) => {
if (!e.data || e.data.type !== "plugin_event") return;
if (e.data.pluginId && e.data.pluginId !== pluginId) return;
handlePluginEvent(e.data.event, e.data.payload);
});
async function pollEvents() {
if (!clientId || polling) return;
polling = true;
try {
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}/plugins/${pluginId}/events`, {
headers: { Accept: "application/json" },
});
if (res.ok) {
const data = await res.json();
if (data.events) data.events.forEach((e) => handlePluginEvent(e.event, e.payload));
}
} catch (_) {
// Polling is best-effort; the next interval can recover.
} finally {
polling = false;
}
}
btn?.addEventListener("click", async () => {
if (!clientId) {
setStatus("Open this plugin from a client row so clientId is present.");
return;
}
setStatus("Requesting host info");
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}/plugins/sample-wasm-hostinfo/event`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ event: "query_host", payload: {} }),
});
if (!res.ok) setStatus(`Send failed: ${res.status}`);
setTimeout(pollEvents, 250);
});
if (clientId) {
setInterval(pollEvents, 1500);
setTimeout(pollEvents, 300);
}
})();
@@ -0,0 +1,11 @@
# Sample WASM Platform Note Plugin
This Plugin 2.0 sample is written in Rust. It reads HostInfo, branches on `os` and `arch`, and writes a small note into the approved `pluginData` bucket.
On Windows, install the Rust WASI target first:
```bat
rustup target add wasm32-wasip1
```
Then run this sample's local `build.bat`. The builder runs Cargo, writes `sample-wasm-platform-note.wasm`, and creates `sample-wasm-platform-note.zip`.
@@ -0,0 +1,76 @@
@echo off
setlocal enabledelayedexpansion
set "PLUGIN_DIR=%~dp0"
set "PLUGIN_NAME=sample-wasm-platform-note"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
set "WASM_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.wasm"
set "ZIP_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.zip"
if not exist "%PLUGIN_DIR%\config.json" (
echo [error] config.json not found in %PLUGIN_DIR%
exit /b 1
)
set "RUST_MANIFEST=%NATIVE_DIR%\Cargo.toml"
if exist "%RUST_MANIFEST%" (
where cargo >nul 2>&1
if errorlevel 1 (
echo [error] cargo was not found. Install Rust or provide %WASM_OUT% yourself.
exit /b 1
)
where rustup >nul 2>&1
if errorlevel 1 (
echo [error] rustup was not found. Install the Rust target manually: rustup target add wasm32-wasip1
exit /b 1
)
rustup target list --installed | findstr /x "wasm32-wasip1" >nul 2>&1
if errorlevel 1 (
echo [setup] Installing Rust target wasm32-wasip1
rustup target add wasm32-wasip1
if errorlevel 1 (
echo [error] Could not install wasm32-wasip1. Run this manually: rustup target add wasm32-wasip1
exit /b 1
)
)
echo [build] cargo build --manifest-path "%RUST_MANIFEST%" --release --target wasm32-wasip1
cargo build --manifest-path "%RUST_MANIFEST%" --release --target wasm32-wasip1
if errorlevel 1 (
echo [error] WASM build failed
exit /b 1
)
copy /Y "%NATIVE_DIR%\target\wasm32-wasip1\release\sample_wasm_platform_note.wasm" "%WASM_OUT%" >nul
if errorlevel 1 (
echo [error] could not copy built WASM to %WASM_OUT%
exit /b 1
)
)
if exist "%ZIP_OUT%" del /f /q "%ZIP_OUT%"
pushd "%PLUGIN_DIR%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$zip = '%ZIP_OUT%'; $items = @(); foreach ($file in @('config.json', '%PLUGIN_NAME%.html', '%PLUGIN_NAME%.css', '%PLUGIN_NAME%.js', '%PLUGIN_NAME%.wasm', 'server.js')) { if (Test-Path -LiteralPath $file -PathType Leaf) { $items += $file } }; foreach ($dir in @('src', 'assets')) { if (Test-Path -LiteralPath $dir -PathType Container) { $items += $dir } }; if ($items.Count -eq 0) { throw 'No plugin files found to package' }; Compress-Archive -Path $items -DestinationPath $zip -Force"
set "ZIP_STATUS=%ERRORLEVEL%"
popd
if not "%ZIP_STATUS%"=="0" exit /b %ZIP_STATUS%
if errorlevel 1 (
echo [error] zip failed
exit /b 1
)
if defined PLUGIN_SIGN_KEY (
where bun >nul 2>&1
if not errorlevel 1 (
echo [sign] Signing plugin with key: %PLUGIN_SIGN_KEY%
bun run "%~dp0..\..\Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
) else (
echo [warn] bun not found, skipping plugin signing
)
)
echo [ok] %ZIP_OUT%
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "sample_wasm_platform_note"
version = "0.1.0"
@@ -0,0 +1,8 @@
[package]
name = "sample_wasm_platform_note"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
path = "src/lib.rs"
@@ -0,0 +1,131 @@
use std::alloc::{alloc, dealloc, Layout};
use std::ptr;
use std::slice;
use std::str;
extern "C" {
fn overlord_emit(event: *const u8, event_len: i32, payload: *const u8, payload_len: i32) -> i32;
fn overlord_host_info(out: *mut u8, out_len: i32) -> i32;
fn overlord_fs_mkdir(bucket: *const u8, bucket_len: i32, path: *const u8, path_len: i32) -> i32;
fn overlord_fs_write(
bucket: *const u8,
bucket_len: i32,
path: *const u8,
path_len: i32,
data: *const u8,
data_len: i32,
) -> i32;
}
#[no_mangle]
pub extern "C" fn overlord_alloc(size: u32) -> *mut u8 {
let size = size.max(1) as usize;
let layout = Layout::from_size_align(size, 8).unwrap();
unsafe { alloc(layout) }
}
#[no_mangle]
pub extern "C" fn overlord_free(ptr: *mut u8, size: u32) {
if ptr.is_null() {
return;
}
let layout = Layout::from_size_align((size.max(1)) as usize, 8).unwrap();
unsafe { dealloc(ptr, layout) };
}
#[no_mangle]
pub extern "C" fn overlord_on_load(_host: *const u8, _host_len: u32) -> i32 {
emit("ready", br#"{"sample":"platform-note"}"#);
0
}
#[no_mangle]
pub extern "C" fn overlord_on_event(
event: *const u8,
event_len: u32,
_payload: *const u8,
_payload_len: u32,
) -> i32 {
let event = unsafe { slice::from_raw_parts(event, event_len as usize) };
if event != b"write_note" {
return 0;
}
let mut host = [0u8; 1024];
let host_len = unsafe { overlord_host_info(host.as_mut_ptr(), host.len() as i32) };
let host = if host_len > 0 {
str::from_utf8(&host[..host_len as usize]).unwrap_or("")
} else {
""
};
let os = if host.contains(r#""os":"windows""#) {
"windows"
} else if host.contains(r#""os":"darwin""#) {
"darwin"
} else if host.contains(r#""os":"linux""#) {
"linux"
} else {
"unknown"
};
let arch = if host.contains(r#""arch":"arm64""#) {
"arm64"
} else if host.contains(r#""arch":"amd64""#) {
"amd64"
} else if host.contains(r#""arch":"386""#) {
"386"
} else {
"unknown"
};
let bucket = "pluginData";
let dir = "platform";
let file = format!("platform/{os}-{arch}.txt");
let note = format!("single WASM plugin running on os={os} arch={arch}\n");
let mkdir_result = unsafe {
overlord_fs_mkdir(
bucket.as_ptr(),
bucket.len() as i32,
dir.as_ptr(),
dir.len() as i32,
)
};
let write_result = unsafe {
overlord_fs_write(
bucket.as_ptr(),
bucket.len() as i32,
file.as_ptr(),
file.len() as i32,
note.as_ptr(),
note.len() as i32,
)
};
let response = format!(
r#"{{"os":"{os}","arch":"{arch}","mkdir":{mkdir_result},"write":{write_result}}}"#
);
emit("platform_note", response.as_bytes());
0
}
#[no_mangle]
pub extern "C" fn overlord_on_unload() {}
fn emit(event: &str, payload: &[u8]) {
unsafe {
overlord_emit(
event.as_ptr(),
event.len() as i32,
payload.as_ptr(),
payload.len() as i32,
);
}
}
#[no_mangle]
pub extern "C" fn memset(dest: *mut u8, value: i32, len: usize) -> *mut u8 {
unsafe { ptr::write_bytes(dest, value as u8, len) };
dest
}
@@ -0,0 +1 @@
{"rustc_fingerprint":2568544898921049753,"outputs":{"7971740275564407648":{"success":true,"status":"","code":0,"stdout":"___.exe\nlib___.rlib\n___.dll\n___.dll\n___.lib\n___.dll\nC:\\Users\\this1\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\npacked\n___\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"msvc\"\ntarget_family=\"windows\"\ntarget_feature=\"cmpxchg16b\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_feature=\"sse3\"\ntarget_has_atomic=\"128\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"windows\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"pc\"\nwindows\n","stderr":""},"5946400966674136012":{"success":true,"status":"","code":0,"stdout":"___.wasm\nlib___.rlib\n___.wasm\nlib___.a\nC:\\Users\\this1\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\noff\n___\ndebug_assertions\npanic=\"abort\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"wasm32\"\ntarget_endian=\"little\"\ntarget_env=\"p1\"\ntarget_family=\"wasm\"\ntarget_feature=\"bulk-memory\"\ntarget_feature=\"multivalue\"\ntarget_feature=\"mutable-globals\"\ntarget_feature=\"nontrapping-fptoint\"\ntarget_feature=\"reference-types\"\ntarget_feature=\"sign-ext\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"wasi\"\ntarget_pointer_width=\"32\"\ntarget_vendor=\"unknown\"\n","stderr":"warning: dropping unsupported crate type `dylib` for target `wasm32-wasip1`\n\nwarning: dropping unsupported crate type `proc-macro` for target `wasm32-wasip1`\n\nwarning: 2 warnings emitted\n\n"},"17747080675513052775":{"success":true,"status":"","code":0,"stdout":"rustc 1.94.0 (4a4ef493e 2026-03-02)\nbinary: rustc\ncommit-hash: 4a4ef493e3a1488c6e321570238084b38948f6db\ncommit-date: 2026-03-02\nhost: x86_64-pc-windows-msvc\nrelease: 1.94.0\nLLVM version: 21.1.8\n","stderr":""}},"successes":{}}
@@ -0,0 +1,3 @@
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by cargo.
# For information about cache directory tags see https://bford.info/cachedir/
@@ -0,0 +1,3 @@
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by cargo.
# For information about cache directory tags see https://bford.info/cachedir/
@@ -0,0 +1,22 @@
#sample-wasm-platform-note-output {
min-height: 8rem;
}
.sample-wasm-platform-note-field {
border: 1px solid rgba(5, 150, 105, 0.45);
background: rgba(6, 78, 59, 0.25);
padding: 0.75rem;
}
.sample-wasm-platform-note-field span {
display: block;
color: rgb(148, 163, 184);
font-size: 0.75rem;
}
.sample-wasm-platform-note-field strong {
display: block;
color: rgb(209, 250, 229);
font-size: 0.95rem;
overflow-wrap: anywhere;
}
@@ -0,0 +1,12 @@
<div class="space-y-3">
<h2 class="text-lg font-semibold text-slate-100">Sample WASM Platform Note</h2>
<button id="sample-wasm-platform-note-run" class="px-3 py-2 rounded-lg border border-emerald-700 bg-emerald-950/40 text-emerald-100">Write platform note</button>
<div id="sample-wasm-platform-note-status" class="text-xs text-slate-400">Waiting to write platform note</div>
<div class="grid gap-2 sm:grid-cols-2">
<div class="sample-wasm-platform-note-field"><span>OS</span><strong id="sample-wasm-platform-note-os">-</strong></div>
<div class="sample-wasm-platform-note-field"><span>Arch</span><strong id="sample-wasm-platform-note-arch">-</strong></div>
<div class="sample-wasm-platform-note-field"><span>mkdir</span><strong id="sample-wasm-platform-note-mkdir">-</strong></div>
<div class="sample-wasm-platform-note-field"><span>write</span><strong id="sample-wasm-platform-note-write">-</strong></div>
</div>
<pre id="sample-wasm-platform-note-output" class="text-xs text-slate-300 whitespace-pre-wrap"></pre>
</div>
@@ -0,0 +1,93 @@
(() => {
const out = document.getElementById("sample-wasm-platform-note-output");
const btn = document.getElementById("sample-wasm-platform-note-run");
const status = document.getElementById("sample-wasm-platform-note-status");
const fields = {
os: document.getElementById("sample-wasm-platform-note-os"),
arch: document.getElementById("sample-wasm-platform-note-arch"),
mkdir: document.getElementById("sample-wasm-platform-note-mkdir"),
write: document.getElementById("sample-wasm-platform-note-write"),
};
const clientId = new URLSearchParams(window.location.search).get("clientId");
const pluginId = "sample-wasm-platform-note";
let polling = false;
function log(message) {
if (out) out.textContent = `${message}\n${out.textContent || ""}`;
}
function setStatus(message) {
if (status) status.textContent = message;
}
function parsePayload(payload) {
if (payload == null) return {};
if (typeof payload === "string") {
try { return JSON.parse(payload); } catch (_) { return { raw: payload }; }
}
return payload;
}
function renderPlatformNote(payload) {
const info = parsePayload(payload);
if (fields.os) fields.os.textContent = info.os || "-";
if (fields.arch) fields.arch.textContent = info.arch || "-";
if (fields.mkdir) fields.mkdir.textContent = String(info.mkdir ?? "-");
if (fields.write) fields.write.textContent = String(info.write ?? "-");
setStatus(info.write === 0 ? "Platform note written" : "Platform note result received");
log(JSON.stringify(info, null, 2));
}
function handlePluginEvent(event, payload) {
if (event === "ready") {
setStatus("Plugin loaded");
log(JSON.stringify(parsePayload(payload), null, 2));
return;
}
if (event === "platform_note") renderPlatformNote(payload);
}
window.addEventListener("message", (e) => {
if (!e.data || e.data.type !== "plugin_event") return;
if (e.data.pluginId && e.data.pluginId !== pluginId) return;
handlePluginEvent(e.data.event, e.data.payload);
});
async function pollEvents() {
if (!clientId || polling) return;
polling = true;
try {
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}/plugins/${pluginId}/events`, {
headers: { Accept: "application/json" },
});
if (res.ok) {
const data = await res.json();
if (data.events) data.events.forEach((e) => handlePluginEvent(e.event, e.payload));
}
} catch (_) {
// Polling is best-effort; the next interval can recover.
} finally {
polling = false;
}
}
btn?.addEventListener("click", async () => {
if (!clientId) {
setStatus("Open this plugin from a client row so clientId is present.");
return;
}
setStatus("Writing platform note");
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}/plugins/sample-wasm-platform-note/event`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ event: "write_note", payload: {} }),
});
if (!res.ok) setStatus(`Send failed: ${res.status}`);
setTimeout(pollEvents, 250);
});
if (clientId) {
setInterval(pollEvents, 1500);
setTimeout(pollEvents, 300);
}
})();
+9
View File
@@ -0,0 +1,9 @@
# Sample WASM Plugin
This is a Plugin 2.0 sample. It declares broad file needs in `config.json`, then uses the agent WASM host imports to write to `pluginData` and list `downloads`.
On Windows, run this sample's local `build.bat`. The builder uses a WASI-capable `clang` to compile `native/sample_wasm.c`, writes `sample-wasm.wasm`, and creates `sample-wasm.zip`.
You can also build `native/sample_wasm.c` manually with a WASI-capable clang, copy the resulting `sample-wasm.wasm` into this folder, then zip the folder contents.
The server will show the declared needs before the module can be sent to an agent.
+60
View File
@@ -0,0 +1,60 @@
@echo off
setlocal enabledelayedexpansion
set "PLUGIN_DIR=%~dp0"
set "PLUGIN_NAME=sample-wasm"
set "NATIVE_DIR=%PLUGIN_DIR%\native"
set "WASM_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.wasm"
set "ZIP_OUT=%PLUGIN_DIR%\%PLUGIN_NAME%.zip"
if not exist "%PLUGIN_DIR%\config.json" (
echo [error] config.json not found in %PLUGIN_DIR%
exit /b 1
)
set "WASM_SOURCE="
if exist "%NATIVE_DIR%" (
for %%S in ("%NATIVE_DIR%\*.c") do (
if not defined WASM_SOURCE set "WASM_SOURCE=%%~fS"
)
)
if defined WASM_SOURCE (
where clang >nul 2>&1
if errorlevel 1 (
echo [error] clang was not found. Install a WASI-capable clang or provide %WASM_OUT% yourself.
exit /b 1
)
echo [build] clang --target=wasm32-wasi -O2 "!WASM_SOURCE!" ^> "%WASM_OUT%"
clang --target=wasm32-wasi -O2 -Wl,--no-entry -Wl,--allow-undefined -Wl,--export=overlord_alloc -Wl,--export=overlord_free -Wl,--export=overlord_on_load -Wl,--export=overlord_on_event -Wl,--export=overlord_on_unload -o "%WASM_OUT%" "!WASM_SOURCE!"
if errorlevel 1 (
echo [error] WASM build failed
exit /b 1
)
)
if exist "%ZIP_OUT%" del /f /q "%ZIP_OUT%"
pushd "%PLUGIN_DIR%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$zip = '%ZIP_OUT%'; $items = @(); foreach ($file in @('config.json', '%PLUGIN_NAME%.html', '%PLUGIN_NAME%.css', '%PLUGIN_NAME%.js', '%PLUGIN_NAME%.wasm', 'server.js')) { if (Test-Path -LiteralPath $file -PathType Leaf) { $items += $file } }; foreach ($dir in @('src', 'assets')) { if (Test-Path -LiteralPath $dir -PathType Container) { $items += $dir } }; if ($items.Count -eq 0) { throw 'No plugin files found to package' }; Compress-Archive -Path $items -DestinationPath $zip -Force"
set "ZIP_STATUS=%ERRORLEVEL%"
popd
if not "%ZIP_STATUS%"=="0" exit /b %ZIP_STATUS%
if errorlevel 1 (
echo [error] zip failed
exit /b 1
)
if defined PLUGIN_SIGN_KEY (
where bun >nul 2>&1
if not errorlevel 1 (
echo [sign] Signing plugin with key: %PLUGIN_SIGN_KEY%
bun run "%~dp0..\..\Overlord-Server\scripts\plugin-sign.ts" --key "%PLUGIN_SIGN_KEY%" "%ZIP_OUT%"
) else (
echo [warn] bun not found, skipping plugin signing
)
)
echo [ok] %ZIP_OUT%
+69
View File
@@ -0,0 +1,69 @@
// Build with a WASI-capable clang:
// clang --target=wasm32-wasi -O2 -Wl,--no-entry -Wl,--export=overlord_alloc \
// -Wl,--export=overlord_free -Wl,--export=overlord_on_load \
// -Wl,--export=overlord_on_event -Wl,--export=overlord_on_unload \
// -o sample-wasm.wasm sample_wasm.c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
__attribute__((import_module("env"), import_name("overlord_emit")))
extern int32_t overlord_emit(const char *event, int32_t event_len, const char *payload, int32_t payload_len);
__attribute__((import_module("env"), import_name("overlord_host_info")))
extern int32_t overlord_host_info(uint8_t *out, int32_t out_len);
__attribute__((import_module("env"), import_name("overlord_fs_mkdir")))
extern int32_t overlord_fs_mkdir(const char *bucket, int32_t bucket_len, const char *path, int32_t path_len);
__attribute__((import_module("env"), import_name("overlord_fs_write")))
extern int32_t overlord_fs_write(const char *bucket, int32_t bucket_len, const char *path, int32_t path_len, const uint8_t *data, int32_t data_len);
__attribute__((import_module("env"), import_name("overlord_fs_list")))
extern int32_t overlord_fs_list(const char *bucket, int32_t bucket_len, const char *path, int32_t path_len, uint8_t *out, int32_t out_len);
void *overlord_alloc(uint32_t size) {
return malloc(size ? size : 1);
}
void overlord_free(void *ptr, uint32_t size) {
(void)size;
free(ptr);
}
int32_t overlord_on_load(const char *host_info, int32_t host_info_len) {
const char *event = "ready";
overlord_emit(event, 5, host_info, host_info_len);
return 0;
}
int32_t overlord_on_event(const char *event, int32_t event_len, const char *payload, int32_t payload_len) {
(void)payload;
(void)payload_len;
if (event_len != 10 || memcmp(event, "run_sample", 10) != 0) return 0;
const char *plugin_data = "pluginData";
const char *downloads = "downloads";
const char *dir = "notes";
const char *file = "notes/sample.txt";
const char *note = "sample wasm plugin wrote this file\n";
int32_t mkdir_result = overlord_fs_mkdir(plugin_data, 10, dir, 5);
int32_t write_result = overlord_fs_write(plugin_data, 10, file, 16, (const uint8_t *)note, (int32_t)strlen(note));
uint8_t list_buf[4096];
int32_t list_result = overlord_fs_list(downloads, 9, "", 0, list_buf, sizeof(list_buf));
uint8_t host_buf[1024];
int32_t host_result = overlord_host_info(host_buf, sizeof(host_buf));
char response[256];
int n = snprintf(response, sizeof(response),
"{\"mkdir\":%d,\"write\":%d,\"downloadsListBytes\":%d,\"hostInfoBytes\":%d}",
mkdir_result, write_result, list_result, host_result);
overlord_emit("sample_result", 13, response, n);
return 0;
}
void overlord_on_unload(void) {}
+3
View File
@@ -0,0 +1,3 @@
#sample-wasm-output {
min-height: 7rem;
}
+6
View File
@@ -0,0 +1,6 @@
<div class="space-y-3">
<h2 class="text-lg font-semibold text-slate-100">Sample WASM</h2>
<p class="text-sm text-slate-400">Plugin 2.0 runtime smoke test.</p>
<button id="sample-wasm-run" class="px-3 py-2 rounded-lg border border-cyan-700 bg-cyan-950/40 text-cyan-100">Run sample event</button>
<pre id="sample-wasm-output" class="text-xs text-slate-300 whitespace-pre-wrap"></pre>
</div>
+22
View File
@@ -0,0 +1,22 @@
(() => {
const out = document.getElementById("sample-wasm-output");
const btn = document.getElementById("sample-wasm-run");
const clientId = new URLSearchParams(window.location.search).get("clientId");
function log(message) {
if (out) out.textContent = `${new Date().toLocaleTimeString()} ${message}\n${out.textContent || ""}`;
}
btn?.addEventListener("click", async () => {
if (!clientId) {
log("Open this plugin from a client row so clientId is present.");
return;
}
const res = await fetch(`/api/clients/${encodeURIComponent(clientId)}/plugins/sample-wasm/event`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ event: "run_sample", payload: { note: "hello from UI" } }),
});
log(res.ok ? "sent run_sample" : `send failed: ${res.status}`);
});
})();