# Nacho Plugin Authoring Guide

Nacho is built on a **Cordis microkernel** (`nacho-kernel`) where every feature — agent loops, LLM providers, tools, runtimes, UI panels, themes, and self-editing devtools — is an equal, hot-swappable plugin.

Plugins compile to **WASM Components (`wasm32-wasip2`)** against the canonical `nacho:kernel@0.1.0` WIT world and can be loaded, hot-swapped, enabled, disabled, or unloaded **live** with zero restart.

---

## 1. Cordis Mental Model

1. **Spatiotemporal Composability (`EffectScope` + LIFO Disposables)**
   - Every plugin mounts into its own `EffectScope`.
   - Every registration (`provide_service`, `subscribe`, `intercept`) returns a handle owned by that scope.
   - Unloading or hot-swapping automatically unwinds all handles in LIFO order with zero leaks.
2. **Reactive Dependency Injection (`provides` & `requires`)**
   - Declare the service keys your plugin exports (`provides`) and depends on (`requires`).
   - Dependents mount automatically when required services appear and cleanly suspend/remount when a provider reloads.
3. **Zero Protected Plugins**
   - Every plugin is equal. Never assume another optional plugin is active; degrade cleanly if a service call returns `service_not_found`.
4. **Atomic Hot-Swap with Rollback**
   - Calling `plugin_load_file` or `plugin_load_wasm` with an existing plugin's `id` hot-swaps the WASM component live. If the new version's `mount()` fails, the kernel rolls back to the previous version automatically.

---

## 2. Quickstart: Write, Build, and Hot-Load a WASM Plugin

### Fast Iteration Setup (1–2s Rebuilds)
Use `plugin_scaffold` (or create a standalone crate under `~/.local/share/nacho/plugins/<name>`) with a shared target directory so `serde`, `wit-bindgen`, `nacho-sdk`, and `nacho-contracts` compile only once:

```bash
rustup target add wasm32-wasip2
CARGO_TARGET_DIR="$HOME/.local/share/nacho/plugin-target" \
  cargo build --manifest-path "$HOME/.local/share/nacho/plugins/my-plugin/Cargo.toml" \
  --target wasm32-wasip2 --release
```

Then load or hot-reload the resulting `.wasm` live via `plugin_load_file` (local) or `plugin_load_wasm` (remote container / base64).

### Minimal `Cargo.toml`
```toml
[package]
name = "my-nacho-plugin"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
nacho-contracts = { git = "https://github.com/OlaHulleberg/nacho", package = "nacho-contracts" }
nacho-sdk = { git = "https://github.com/OlaHulleberg/nacho", package = "nacho-sdk" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[profile.release]
opt-level = "s"
debug = 0
```
*(When working inside a local checkout of Nacho, you may also point `nacho-contracts` and `nacho-sdk` at local `path = ".../crates/nacho-contracts"` / `".../crates/nacho-sdk"`.)*

### Minimal `src/lib.rs` (WASM Component)
```rust
use nacho_contracts::services;
use nacho_sdk::{Manifest, NachoPlugin, Payload, PluginCtx, PluginError, export_plugin};
use serde_json::json;

#[derive(Default)]
struct MyPlugin;

impl NachoPlugin for MyPlugin {
    fn describe(&self) -> Manifest {
        Manifest {
            id: "community.my-plugin".to_owned(),
            version: "0.1.0".to_owned(),
            provides: vec!["service.my_plugin".to_owned()],
            requires: vec![services::STORAGE.to_owned()],
        }
    }

    fn mount(&self, ctx: PluginCtx, _config: Payload) -> Result<(), PluginError> {
        ctx.provide_service("service.my_plugin")?;
        Ok(())
    }

    fn unmount(&self, _ctx: PluginCtx) -> Result<(), PluginError> {
        Ok(())
    }

    fn invoke_service(
        &self,
        _ctx: PluginCtx,
        _service: &str,
        method: &str,
        _input: Payload,
    ) -> Result<Payload, PluginError> {
        match method {
            "ping" => Payload::json(&json!({ "ok": true })),
            other => Err(PluginError::new("unknown_method", format!("unsupported {other}"))),
        }
    }
}

export_plugin!(MyPlugin);
```

---

## 3. WIT Interface (`nacho:kernel@0.1.0`) & `PluginCtx`

Every plugin imports `host` and exports `lifecycle` (generated automatically by `nacho_sdk::export_plugin!`):

| `PluginCtx` method | Purpose |
|---|---|
| `provide_service(service)` | Expose `service` routed to `invoke_service`. |
| `call_service(service, method, payload)` / `call_json(...)` | Call any active kernel or plugin service. |
| `subscribe(topic)` | Subscribe to broadcast events dispatched to `on_event`. |
| `intercept(topic, priority)` | Register a waterfall interceptor dispatched to `on_intercept` (lower priority runs first; return `InterceptOutcome::Pass(payload)` or `InterceptOutcome::Halt(payload)`). |
| `emit(topic, payload)` | Emit a topic event through interceptors and subscribers. |
| `dispose(handle)` | Release a registration handle early. |
| `log(level, message)` | Emit a host log line. |

---

## 4. Core & Standard Service Directory

All service keys are defined in `nacho_contracts::services`:

| Service Key | Key Methods | Purpose |
|---|---|---|
| `service.storage` | `kv_get`, `kv_put`, `kv_delete`, `kv_list`, `log_append`, `log_read` | Persistent SQLite KV store (namespaced) & append-only event logs. |
| `service.ui` | `register_surface`, `register_provider`, `set_theme_patch`, `set_layout_patch`, `unregister_plugin`, `get_snapshot`, `dispatch_action` | Declarative UI composition, themes, layouts, and interactive actions. |
| `service.tools` | `list_defs`, `register_tool`, `unregister_plugin`, `invoke` | Dynamic LLM agent tool registry. |
| `service.kernel_control` | `status`, `load_plugin`, `load_plugin_file`, `reload_plugin`, `schedule_reload_plugin`, `enable_plugin`, `disable_plugin`, `unload_plugin`, `revert_plugin`, `list_persisted` | Live plugin lifecycle & WASM persistence. |
| `service.plugin_repos` | `get_state`, `add_repo`, `remove_repo`, `toggle_repo`, `refresh_repos`, `install_plugin`, `update_plugin`, `update_all`, `revert_plugin` | Signed plugin repository catalog & installs. |
| `service.session` | `create_session`, `create_child_session`, `delete_session`, `append_event`, `get_events`, `fork_session`, `list_sessions`, `get_checkpoint`, `save_checkpoint` | Conversation threads & durable checkpoints. |
| `service.providers` | `get_state`, `register_provider`, `unregister_provider`, `save_provider`, `select_model`, `set_reasoning`, `resolve_model`, `refresh_models` | Model provider registry & active model selection. |
| `service.projects` | `list`, `add`, `select`, `remove`, `git_status`, `git_diff`, `list_files`, `read_file` | Local project directories & git status/diffs. |
| `service.runtimes` | `list`, `set_default`, `get_thread_runtime`, `set_thread_runtime`, `run_turn`, `compute_status` | Local & remote compute runtime targets. |
| `service.workspace` | `read_file`, `write_file`, `delete_file`, `list_files`, `snapshot`, `file_sizes` | Session virtual filesystem. |
| `service.http` | `request` | Generic outbound HTTP client. |
| `service.fs_local` | `read`, `write`, `edit`, `list`, `search` | Scoped local filesystem operations. |
| `service.shell_local` | `run`, `cancel` | Scoped local shell execution. |
| `service.git_local` | `status`, `diff`, `worktree_add`, `worktree_remove` | Local git inspection & worktrees. |
| `service.devtools` | `get_permissions`, `set_permission`, `reset_overrides`, `invoke_tool`, `ui_action` | Self-editing devtools & scoped agent permissions. |

---

## 5. Event Topics & Waterfall Interceptors

All standard topic names live in `nacho_contracts::topics`:
- `ui.updated` — triggers live GPUI snapshot refresh (always emit after mutating UI state in `service.storage`!).
- `session.event` — emitted whenever an event is appended to a thread.
- `agent.step`, `agent.thinking`, `agent.delta`, `agent.tool_call`, `agent.tool_result`, `agent.done`, `agent.cancelled` — durable agent loop lifecycle.
- `exec.output` — live command output chunks.
- `orchestration.updated`, `swarm.updated`, `github.updated` — subsystem updates.

### Registering a Custom Agent Tool Plugin
1. Call `service.tools` → `"register_tool"` with `RegisterToolReq { plugin_id, service, def: ToolDef { name, description, parameters } }` in `mount()`.
2. Handle `method == "invoke_tool"` on your plugin's service, decoding `InvokeToolReq { session_id, tool_name, arguments }` and returning `InvokeToolRes { ok, summary, output, file_path, additions, deletions, backend_used, exit_code }`.
3. Call `service.tools` → `"unregister_plugin"` with `{ "plugin_id": ID }` in `unmount()`.

---

## 6. Agent Self-Editing Permissions & Recovery

The `nacho.plugin-devtools` plugin exposes live self-editing tools grouped into 4 scopes (all **enabled by default**, and toggleable anytime in **Settings → Devtools** or by disabling the plugin completely):
- **`inspect`**: `plugin_list`, `ui_inspect`, `nacho_docs`, `plugin_repo_list`
- **`live_ui`**: `ui_set_theme`, `ui_set_layout`, `ui_register_surface`, `ui_remove_surface`
- **`plugin_toggle`**: `plugin_enable`, `plugin_disable`, `plugin_revert`
- **`plugin_install`**: `plugin_load_file`, `plugin_load_wasm`, `plugin_unload`, `plugin_install`, `plugin_repo_add`, `plugin_repo_refresh`, `plugin_scaffold`

### Safe-Mode Recovery
If a custom UI plugin or disabled UI panel ever breaks your layout, launch with `--safe-mode`:
```bash
nacho-gpui --safe-mode
# or
nacho-host-local serve --safe-mode
```
Safe mode skips loading persisted WASM overrides and persisted disabled-plugin states for that boot so you can inspect, fix, or revert plugins cleanly.
