rsclaw-plugin 0.1.0

Plugin crate for RsClaw — internal workspace crate, not for direct use
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Plugin manifest parser.
//!
//! Every plugin lives in its own directory under `~/.rsclaw/plugins/<name>/`.
//! rsclaw looks for a manifest file in this order:
//!   1. `plugin.json5`          — rsclaw native format (json5, supports wasm +
//!      js)
//!   2. `openclaw.plugin.json`  — OpenClaw compatibility (json, js-only)
//!
//! Example `plugin.json5`:
//! ```json5
//! {
//!   name: "myplugin",
//!   version: "1.0.0",
//!   description: "What the plugin does (shown to the LLM)",
//!   runtime: "wasm",            // "wasm" | "js" | "node" | "bun" | "deno"
//!   entry: "./myplugin.wasm",   // or "./dist/index.js"
//!   tools: [
//!     {
//!       name: "do_thing",
//!       description: "Do the thing",
//!       inputSchema: { type: "object", properties: {} }
//!     }
//!   ]
//! }
//! ```

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// rsclaw native manifest filename.
pub const MANIFEST_FILE: &str = "plugin.json5";

/// OpenClaw compatibility manifest filename.
pub const LEGACY_MANIFEST_FILE: &str = "openclaw.plugin.json";

// ---------------------------------------------------------------------------
// PluginManifest
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginManifest {
    /// Unique plugin name (slug).
    /// rsclaw uses `name`; OpenClaw extensions use `id`. Both are accepted.
    #[serde(default)]
    pub name: String,
    /// OpenClaw extension ID (fallback for `name`).
    #[serde(default)]
    pub id: Option<String>,
    /// Semver version string.
    pub version: Option<String>,
    /// Human-readable description.
    pub description: Option<String>,
    /// One-line catalog blurb shown in the `## Installed Plugins` prompt
    /// section. Falls back to `description` when absent.
    #[serde(default)]
    pub summary: Option<String>,
    /// Tool names to surface as "common" in the catalog (the rest are found
    /// via plugin_search). Empty → renderer shows the first few + count.
    #[serde(default, rename = "commonTools")]
    pub common_tools: Vec<String>,
    /// Runtime: "node" | "bun" | "deno" | "wasm". Defaults to "node".
    /// The legacy/generic "js" runtime is accepted and normalized to "node".
    #[serde(default = "default_runtime")]
    pub runtime: String,
    /// Entry point relative to the plugin directory.
    /// e.g. `"./myplugin.wasm"` or `"./dist/index.js"`.
    /// Optional for OpenClaw extensions (defaults to `"./dist/index.js"`).
    #[serde(default = "default_entry")]
    pub entry: String,
    /// Optional integrity digest for the entry file. Currently supports
    /// `sha256:<hex>`. WASM plugins that declare this must match before
    /// the host compiles the component.
    #[serde(default)]
    pub integrity: Option<String>,
    /// Channels this plugin provides (OpenClaw extension field).
    #[serde(default)]
    pub channels: Vec<String>,
    /// Slots this plugin fills: `"memory"` | `"context_engine"`.
    #[serde(default)]
    pub slots: Vec<String>,
    /// Lifecycle hooks this plugin subscribes to.
    #[serde(default)]
    pub hooks: Vec<String>,
    /// Additional tool definitions exposed by this plugin.
    #[serde(default)]
    pub tools: Vec<PluginToolDef>,
    /// v2 toolGroups metadata: group name → one-line description, shown in
    /// the `request_tool` stub so the model knows what enabling buys.
    /// Tools opt into a group via their own `group` field; a name listed
    /// here with no member tools is simply never offered.
    #[serde(default, rename = "toolGroups")]
    pub tool_groups: std::collections::HashMap<String, String>,
    /// Minimum interval between tool calls in milliseconds. The host enforces
    /// this for wasm plugins (replaces the old plugin-side `host::sleep` at
    /// the top of every dispatch). Default: 0 (no throttling).
    #[serde(default)]
    pub min_call_interval_ms: u32,
    /// Per-call timeout in milliseconds for JS-runtime plugins. The host
    /// drops the pending oneshot after this. Default 30s; raise for plugins
    /// whose tools include long-running browser flows (login, booking).
    /// Plugin-wide; per-tool override is a future enhancement.
    pub timeout_ms: Option<u64>,
    /// Minimum rsclaw version required.
    pub requires_rsclaw: Option<String>,
    /// Plugin-declared CDN routing rules. The host applies them when this
    /// plugin invokes `host::browser_download(url, ...)` so the host stays
    /// agnostic to per-platform auth quirks (Bytedance referers, etc.).
    /// Default is empty — most plugins don't need this.
    #[serde(default)]
    pub browser_cdn: BrowserCdnConfig,
    /// Arbitrary extra fields for future compatibility.
    #[serde(default, flatten)]
    pub extra: HashMap<String, Value>,
    /// Plugin-specific configuration block. The host resolves simple
    /// secret references before exposing it to trusted WASM plugins via
    /// `host-config`.
    #[serde(default)]
    pub config: Value,
    /// Capability names requested by this plugin. Dangerous capabilities
    /// such as background workers, outbound push, and tool aliases are
    /// honored only for trusted plugins.
    #[serde(default)]
    pub capabilities: Vec<String>,
    /// Slash command prefixes this plugin wants to handle locally.
    #[serde(default, rename = "slashCommands")]
    pub slash_commands: Vec<PluginSlashCommand>,
    /// Optional trusted aliases from plugin tool names to first-class
    /// tool names. Example: `{ quote: "stock_quote" }`.
    #[serde(default, rename = "toolAliases")]
    pub tool_aliases: HashMap<String, String>,

    // --- runtime fields (not in JSON) ---
    /// Absolute path to the plugin directory.
    #[serde(skip)]
    pub dir: PathBuf,
}

fn default_entry() -> String {
    "./dist/index.js".to_owned()
}

/// Plugin-declared rules for the host's CDN-aware downloader.
///
/// Each plugin owns the knowledge of *its* platform's CDN auth quirks —
/// not the host. Bytedance's vlabvod gates signed URLs on a Referer of
/// `jimeng.jianying.com`; Douyin's douyinpic/douyinvod gate on
/// `www.douyin.com`. The host has no business knowing either fact —
/// it just looks up the rule the calling plugin declared.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserCdnConfig {
    /// Per-host download rules. When the URL's host substring-matches any
    /// entry in `match_hosts`, the rule applies and `referer` is forwarded
    /// to the host's downloader.
    #[serde(default)]
    pub download_rules: Vec<CdnDownloadRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CdnDownloadRule {
    /// URL host substrings; ANY match triggers the rule. First matching
    /// rule wins (so order rules from most-specific to most-general).
    pub match_hosts: Vec<String>,
    /// Referer header to forward when downloading from a matching URL.
    pub referer: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginToolDef {
    pub name: String,
    pub description: String,
    pub input_schema: Option<Value>,
    /// Plugin-author-declared default exposure. When `true`, this tool
    /// is auto-promoted into `req.tools` (real ToolDef in
    /// `dynamic_prefix.user_tools`) for every agent that activates this
    /// plugin — bypassing the `plugin_search` → `plugin_describe` →
    /// `plugin_invoke` three-step dance that small (9B-class) models
    /// can't reliably navigate. Non-headline tools stay accessible
    /// through the existing `plugin_invoke` meta-tool but consume zero
    /// prompt tokens until called.
    ///
    /// Choose ~5–15 of the plugin's most-used tools. The cap on
    /// concurrently-exposed plugin tools per turn is set by
    /// `model.user_tools_cap` (default 30 in v1.9); excess headlines
    /// across active plugins are truncated round-robin. Operators can
    /// override at deployment time via `model.plugin_tools`
    /// (additive pin) and `model.plugin_tools_unpin` (subtractive),
    /// or at runtime via `/plugin pin <name>` / `/plugin unpin <name>`.
    ///
    /// Defaults to `false` so an unspecified tool stays in the long
    /// tail — a missing `headline:` key never changes behavior.
    #[serde(default)]
    pub headline: bool,
    /// Feature group this tool belongs to (v2 toolGroups). Groups are the
    /// unit of on-demand exposure: the prompt carries a one-line stub per
    /// group and `request_tool("<plugin>:<group>")` splices the group's
    /// real ToolDefs in. Ungrouped tools keep headline/search behavior.
    #[serde(default)]
    pub group: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginSlashCommand {
    /// Command prefix, for example `/myplugin`.
    pub prefix: String,
    /// Tool name inside this plugin that handles the slash payload.
    pub handler: String,
}

fn default_runtime() -> String {
    "node".to_owned()
}

impl PluginManifest {
    /// Normalize after parsing: resolve `id` -> `name` fallback.
    fn normalize(&mut self) {
        // OpenClaw uses `id`, rsclaw uses `name`.
        if self.name.is_empty() {
            if let Some(ref id) = self.id {
                self.name = id.clone();
            }
        }
        if self.runtime.trim().is_empty() || self.runtime == "js" {
            self.runtime = default_runtime();
        }
    }

    /// Whether this plugin uses the WASM runtime.
    pub fn is_wasm(&self) -> bool {
        self.runtime == "wasm"
    }

    /// Whether this is an OpenClaw channel extension.
    pub fn is_channel_extension(&self) -> bool {
        !self.channels.is_empty()
    }

    /// Resolve the absolute path to the entry point.
    pub fn entry_path(&self) -> PathBuf {
        self.dir.join(&self.entry)
    }
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Load a plugin manifest from a directory.
///
/// Tries `plugin.json5` first, then falls back to `openclaw.plugin.json`.
pub fn load_manifest(plugin_dir: &Path) -> Result<PluginManifest> {
    let json5_path = plugin_dir.join(MANIFEST_FILE);
    let legacy_path = plugin_dir.join(LEGACY_MANIFEST_FILE);

    if json5_path.exists() {
        load_manifest_json5(&json5_path, plugin_dir)
    } else if legacy_path.exists() {
        load_manifest_json(&legacy_path, plugin_dir)
    } else {
        anyhow::bail!(
            "no manifest found in {} (expected {} or {})",
            plugin_dir.display(),
            MANIFEST_FILE,
            LEGACY_MANIFEST_FILE,
        )
    }
}

/// Parse a `plugin.json5` manifest.
fn load_manifest_json5(path: &Path, plugin_dir: &Path) -> Result<PluginManifest> {
    let raw =
        std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;

    let mut manifest: PluginManifest = json5::from_str(&raw)
        .with_context(|| format!("json5 parse error in {}", path.display()))?;

    manifest.dir = plugin_dir.to_path_buf();
    manifest.normalize();
    Ok(manifest)
}

/// Parse a legacy `openclaw.plugin.json` manifest.
fn load_manifest_json(path: &Path, plugin_dir: &Path) -> Result<PluginManifest> {
    let raw =
        std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;

    let mut manifest: PluginManifest = serde_json::from_str(&raw)
        .with_context(|| format!("JSON parse error in {}", path.display()))?;

    manifest.dir = plugin_dir.to_path_buf();
    manifest.normalize();
    Ok(manifest)
}

/// Scan a directory for plugin sub-directories (each must have a manifest).
pub fn scan_plugins(plugins_dir: &Path) -> Result<Vec<PluginManifest>> {
    if !plugins_dir.exists() {
        return Ok(Vec::new());
    }

    let mut manifests = Vec::new();

    for entry in std::fs::read_dir(plugins_dir)
        .with_context(|| format!("read plugins dir: {}", plugins_dir.display()))?
        .flatten()
    {
        let plugin_dir = entry.path();
        if !plugin_dir.is_dir() {
            continue;
        }
        // Must have at least one manifest file.
        let has_manifest = plugin_dir.join(MANIFEST_FILE).exists()
            || plugin_dir.join(LEGACY_MANIFEST_FILE).exists();
        if !has_manifest {
            continue;
        }
        match load_manifest(&plugin_dir) {
            Ok(m) => manifests.push(m),
            Err(e) => {
                tracing::warn!(
                    path = %plugin_dir.display(),
                    "failed to load plugin manifest: {e:#}"
                );
            }
        }
    }

    Ok(manifests)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn write_file(dir: &Path, name: &str, content: &str) {
        std::fs::write(dir.join(name), content).expect("write file");
    }

    #[test]
    fn manifest_parses_summary_and_common_tools() {
        let json5 = r#"{
            name: "demo",
            version: "1.0.0",
            description: "d",
            summary: "Does demo things",
            commonTools: ["publish", "list"],
            tools: [{ name: "publish", description: "p" }],
        }"#;
        let m: PluginManifest = json5::from_str(json5).unwrap();
        assert_eq!(m.summary.as_deref(), Some("Does demo things"));
        assert_eq!(
            m.common_tools,
            vec!["publish".to_string(), "list".to_string()]
        );

        // Backward compat: absent fields default cleanly.
        let bare = r#"{ name: "x", tools: [] }"#;
        let m2: PluginManifest = json5::from_str(bare).unwrap();
        assert!(m2.summary.is_none());
        assert!(m2.common_tools.is_empty());
    }

    #[test]
    fn parse_json5_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_file(
            tmp.path(),
            MANIFEST_FILE,
            r#"{
  name: "test-wasm",
  version: "2.0.0",
  description: "A WASM plugin",
  runtime: "wasm",
  entry: "./plugin.wasm",
  integrity: "sha256:0123456789abcdef",
  tools: [
    {
      name: "do_thing",
      description: "Does things",
      inputSchema: { type: "object" }
    }
  ]
}"#,
        );

        let m = load_manifest(tmp.path()).expect("load");
        assert_eq!(m.name, "test-wasm");
        assert_eq!(m.version.as_deref(), Some("2.0.0"));
        assert_eq!(m.runtime, "wasm");
        assert_eq!(m.integrity.as_deref(), Some("sha256:0123456789abcdef"));
        assert!(m.is_wasm());
        assert_eq!(m.tools.len(), 1);
    }

    #[test]
    fn parse_legacy_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_file(
            tmp.path(),
            LEGACY_MANIFEST_FILE,
            r#"{"name": "legacy", "entry": "./index.js"}"#,
        );

        let m = load_manifest(tmp.path()).expect("load");
        assert_eq!(m.name, "legacy");
        assert_eq!(m.runtime, "node"); // default
        assert!(!m.is_wasm());
    }

    #[test]
    fn json5_takes_priority_over_legacy() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_file(
            tmp.path(),
            MANIFEST_FILE,
            r#"{ name: "native", entry: "./plugin.wasm", runtime: "wasm" }"#,
        );
        write_file(
            tmp.path(),
            LEGACY_MANIFEST_FILE,
            r#"{"name": "legacy", "entry": "./index.js"}"#,
        );

        let m = load_manifest(tmp.path()).expect("load");
        assert_eq!(m.name, "native");
        assert!(m.is_wasm());
    }

    #[test]
    fn parse_minimal_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_file(
            tmp.path(),
            MANIFEST_FILE,
            r#"{ name: "minimal", entry: "./main.js" }"#,
        );

        let m = load_manifest(tmp.path()).expect("load");
        assert_eq!(m.name, "minimal");
        assert_eq!(m.runtime, "node");
        assert!(m.slots.is_empty());
    }

    #[test]
    fn parse_js_runtime_alias_as_node() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_file(
            tmp.path(),
            MANIFEST_FILE,
            r#"{ name: "travel", entry: "./src/index.mjs", runtime: "js" }"#,
        );

        let m = load_manifest(tmp.path()).expect("load");
        assert_eq!(m.runtime, "node");
        assert!(!m.is_wasm());
    }

    #[test]
    fn scan_plugins_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        // Native plugin with plugin.json5
        let dir_a = tmp.path().join("plugin-a");
        std::fs::create_dir_all(&dir_a).expect("mkdir");
        write_file(
            &dir_a,
            MANIFEST_FILE,
            r#"{ name: "plugin-a", entry: "./a.wasm", runtime: "wasm" }"#,
        );
        // Legacy plugin with openclaw.plugin.json
        let dir_b = tmp.path().join("plugin-b");
        std::fs::create_dir_all(&dir_b).expect("mkdir");
        write_file(
            &dir_b,
            LEGACY_MANIFEST_FILE,
            &format!(r#"{{"name":"plugin-b","entry":"./index.js"}}"#),
        );
        // A directory without manifest should be ignored.
        std::fs::create_dir_all(tmp.path().join("no-manifest")).expect("mkdir");

        let plugins = scan_plugins(tmp.path()).expect("scan");
        assert_eq!(plugins.len(), 2);
    }
}