Skip to main content

objectiveai_cli/filesystem/plugins/
manifest.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4use crate::filesystem::tools::{CliZip, Exec};
5
6/// Declarative metadata a plugin ships with — the on-disk
7/// `objectiveai.json` at
8/// `<base_dir>/plugins/<owner>/<name>/<version>/objectiveai.json`. The
9/// CLI reads and writes this shape verbatim (install writes the fetched
10/// manifest exactly as authored); the `plugins get` wire response is a
11/// lean projection of it.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
13#[schemars(rename = "filesystem.plugins.Manifest")]
14pub struct Manifest {
15    /// GitHub `<owner>` segment of the source repo, written verbatim
16    /// from the fetched manifest (forks land on disk with whatever
17    /// owner they authored, not rewritten to the install coordinate).
18    pub owner: String,
19
20    /// The plugin's identifier (matches the `<name>` directory
21    /// segment).
22    pub name: String,
23
24    /// Version string. Semver convention is recommended but not
25    /// enforced — the host just displays whatever's here.
26    pub version: String,
27
28    /// One-line description of what the plugin does. Surfaced in
29    /// listings and the plugin's `--help`-equivalent UI.
30    pub description: String,
31
32    /// Per-OS exec command for the plugin's cli side — the same shape
33    /// tools use. The current platform's vector is the program plus
34    /// its leading arguments; the run's args are appended, and the
35    /// whole thing runs with CWD = `<plugin dir>/cli/`. Relative
36    /// program paths resolve against that folder; bare names keep
37    /// PATH-lookup semantics. An empty per-OS vector means viewer-only
38    /// for that platform.
39    pub exec: Exec,
40
41    /// Per-OS cli bundle zip filenames. At install the current
42    /// platform's entry (when present) is downloaded and extracted
43    /// into `<plugin dir>/cli/` (the [`Self::exec`] working
44    /// directory), the same way [`Self::viewer_zip`] extracts to
45    /// `viewer/`. Required field; each per-OS entry is optional —
46    /// absent means the exec needs nothing on disk for that platform
47    /// (e.g. it invokes a PATH-resolved program, or the plugin is
48    /// viewer-only).
49    pub cli_zip: CliZip,
50
51    /// GitHub-release asset filename for the plugin's viewer UI
52    /// bundle (a `.zip` whose root contains `index.html` plus
53    /// assets). When absent, the plugin has no viewer tab from this
54    /// source. Mutually exclusive with [`Self::viewer_url`] —
55    /// validated by [`Self::validate`].
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    #[schemars(extend("omitempty" = true))]
58    pub viewer_zip: Option<String>,
59
60    /// Remote URL the viewer's iframe loads directly, instead of an
61    /// on-disk bundle from [`Self::viewer_zip`]. The full URL is used
62    /// as the iframe `src=` verbatim — query string, path, port,
63    /// fragment all pass through. Must use `https://`, or `http://`
64    /// targeting `localhost` / `127.0.0.1` (development only).
65    ///
66    /// Mutually exclusive with [`Self::viewer_zip`]. The iframe
67    /// receives the same postMessage protocol regardless of where its
68    /// HTML/JS loaded from.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    #[schemars(extend("omitempty" = true))]
71    pub viewer_url: Option<String>,
72
73    /// MCP servers the plugin wants the host to expose. Each entry
74    /// has a `name` (the identifier agents reference via
75    /// [`objectiveai_sdk::agent::ClientObjectiveaiMcpPluginEntry::mcp_servers`])
76    /// plus an `authorization` flag. Auth-requiring entries flag
77    /// `authorization = true`; credentials are resolved by the host
78    /// (env vars / config), not the manifest.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    #[schemars(extend("omitempty" = true))]
81    pub mcp_servers: Vec<McpServer>,
82
83    /// When `true`, the plugin participates in the per-state plugin
84    /// daemon (`daemon spawn`): the daemon launches it as
85    /// `<exec> daemon begin` (via the shared plugin executor) and keeps
86    /// it resident. Host-internal — not surfaced on the `plugins get`
87    /// wire projection. Skipped on serialization when `false` so
88    /// non-daemon manifests stay lean.
89    #[serde(default, skip_serializing_if = "is_false")]
90    #[schemars(extend("omitempty" = true))]
91    pub daemon: bool,
92}
93
94fn is_false(value: &bool) -> bool {
95    !*value
96}
97
98impl Manifest {
99    /// Whether this plugin presents a viewer tab in the host. True
100    /// iff either viewer source field — [`Self::viewer_zip`] or
101    /// [`Self::viewer_url`] — is set.
102    pub fn has_viewer(&self) -> bool {
103        self.viewer_zip.is_some() || self.viewer_url.is_some()
104    }
105
106    /// Validate fields that can't be enforced by serde alone:
107    /// `viewer_zip` and `viewer_url` are mutually exclusive, and
108    /// `viewer_url` (when present) must be `https://` or `http://`
109    /// targeting `localhost` / `127.0.0.1`. Called at every parse
110    /// boundary (remote-fetched install, on-disk read) so a broken
111    /// manifest can't sneak through.
112    pub fn validate(&self) -> Result<(), &'static str> {
113        if self.viewer_zip.is_some() && self.viewer_url.is_some() {
114            return Err("viewer_zip and viewer_url are mutually exclusive");
115        }
116        if let Some(url) = self.viewer_url.as_deref() {
117            validate_viewer_url(url)?;
118        }
119        // Each MCP-server entry needs a non-empty name; the list as a
120        // whole must have no `name` duplicates (since agents reference
121        // by name).
122        for entry in &self.mcp_servers {
123            if entry.name.is_empty() {
124                return Err("mcp_servers[i].name cannot be empty");
125            }
126        }
127        for (i, a) in self.mcp_servers.iter().enumerate() {
128            for b in &self.mcp_servers[i + 1..] {
129                if a.name == b.name {
130                    return Err("mcp_servers contains duplicate name");
131                }
132            }
133        }
134        Ok(())
135    }
136}
137
138/// Allow `https://*`. Allow `http://` only when the host is
139/// `localhost` or `127.0.0.1` (development). Reject everything else
140/// — raw http on a public hostname inside a Tauri WebView is a
141/// footgun (plaintext, MITM-able, mixed-content-blocked by the
142/// browser engine in most cases).
143///
144/// Dependency-free: a couple of `starts_with` / split checks beat
145/// pulling the full `url` crate for one validation. Doesn't handle
146/// IPv6 brackets or punycode — neither matters for the localhost
147/// allow-list.
148fn validate_viewer_url(url: &str) -> Result<(), &'static str> {
149    let url = url.trim();
150    if url.is_empty() {
151        return Err("viewer_url cannot be empty");
152    }
153    if url.starts_with("https://") {
154        return Ok(());
155    }
156    if let Some(rest) = url.strip_prefix("http://") {
157        // Host ends at the first '/', ':', '?', '#', or EOF.
158        let host_end = rest
159            .find(|c: char| matches!(c, '/' | ':' | '?' | '#'))
160            .unwrap_or(rest.len());
161        let host = &rest[..host_end];
162        if host == "localhost" || host == "127.0.0.1" {
163            return Ok(());
164        }
165        return Err(
166            "viewer_url with http:// scheme is only allowed for localhost or 127.0.0.1",
167        );
168    }
169    Err("viewer_url must use https:// or http://localhost / http://127.0.0.1")
170}
171
172/// MCP server entry inside [`Manifest::mcp_servers`]. A host-exposed
173/// upstream identified by a `name` that agent declarations reference
174/// (via
175/// [`objectiveai_sdk::agent::ClientObjectiveaiMcpPluginEntry::mcp_servers`]),
176/// plus an `authorization` flag.
177#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
178#[schemars(rename = "filesystem.plugins.McpServer")]
179pub struct McpServer {
180    /// Author-chosen identifier. Unique per plugin manifest. Agents
181    /// declare which subset of the plugin's MCP servers they want
182    /// exposed by listing names here.
183    pub name: String,
184    /// Whether the host should attach an `Authorization` header
185    /// when dialing this upstream. Credentials are resolved by the
186    /// host (env vars / config), not the manifest.
187    #[serde(default)]
188    pub authorization: bool,
189}
190
191// Typed conversion to the SDK's lean `plugins get` wire shape — drops
192// the on-disk-only fields (`cli_zip`, `viewer_zip`). Lets the
193// `command::plugins::{get, list}` leaves yield SDK `ResponseManifest`
194// items without round-tripping through `serde_json::Value`. The inner
195// type parallel (`McpServer`/`ResponseMcpServer`) is field-identical —
196// collapsing them into a shared type is a separate cleanup pass.
197// `exec` is the SDK type already.
198impl From<Manifest> for objectiveai_sdk::cli::command::plugins::get::ResponseManifest {
199    fn from(m: Manifest) -> Self {
200        use objectiveai_sdk::cli::command::plugins::get::{
201            ResponseManifest, ResponseMcpServer,
202        };
203        ResponseManifest {
204            owner: m.owner,
205            name: m.name,
206            version: m.version,
207            description: m.description,
208            exec: m.exec,
209            viewer_url: m.viewer_url,
210            mcp_servers: m
211                .mcp_servers
212                .into_iter()
213                .map(|s| ResponseMcpServer {
214                    name: s.name,
215                    authorization: s.authorization,
216                })
217                .collect(),
218        }
219    }
220}