Skip to main content

graphrt_core/
catalog.rs

1//! Node catalog: machine-readable descriptions of node kinds.
2//!
3//! Every node kind can publish a [`NodeDescriptor`] (title, category, config
4//! JSON Schema, outputs, branch handles). A visual builder uses the catalog to
5//! render palettes and config forms, and to validate documents before they
6//! reach a runtime. Plugins publish descriptors through their manifests, so a
7//! plugin's nodes appear in the catalog exactly like built-in ones.
8
9use serde::{Deserialize, Serialize};
10
11use crate::value::ValueType;
12
13/// Broad grouping used by builders to organize the node palette.
14#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
15#[serde(rename_all = "kebab-case")]
16#[non_exhaustive]
17pub enum NodeCategory {
18    /// Entry / exit / answer nodes.
19    Io,
20    /// Branching, loops, iteration.
21    Logic,
22    /// Data transformation (templates, assigners, list operations).
23    Transform,
24    /// Model-backed nodes (LLM, classifier, extractor, agent).
25    Model,
26    /// Knowledge / retrieval nodes.
27    Knowledge,
28    /// External integrations (HTTP, tools, code).
29    Integration,
30    /// Human-in-the-loop nodes.
31    Human,
32    /// Anything else, including most plugin nodes.
33    #[default]
34    Other,
35}
36
37/// How a node selects outgoing edges.
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(tag = "kind", rename_all = "snake_case")]
40#[non_exhaustive]
41pub enum Handles {
42    /// Every outgoing edge uses the default `source` handle.
43    #[default]
44    Single,
45    /// A fixed set of handles.
46    Fixed { handles: Vec<String> },
47    /// Handles are derived from configuration (e.g. if-else case ids, classifier class ids).
48    /// `config_path` points at the config field listing them, for builders.
49    Dynamic {
50        #[serde(default, skip_serializing_if = "Option::is_none")]
51        config_path: Option<String>,
52    },
53}
54
55/// One declared output of a node.
56///
57/// Unknown keys are rejected so a typo in a plugin manifest (`streming`) fails at
58/// load time instead of being ignored.
59#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct OutputDescriptor {
62    pub name: String,
63    #[serde(rename = "type")]
64    pub ty: ValueType,
65    #[serde(default, skip_serializing_if = "String::is_empty")]
66    pub description: String,
67    /// Whether this output is streamed incrementally (`node_chunk` events).
68    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
69    pub streaming: bool,
70}
71
72impl OutputDescriptor {
73    pub fn new(name: impl Into<String>, ty: ValueType) -> Self {
74        Self { name: name.into(), ty, description: String::new(), streaming: false }
75    }
76
77    pub fn describe(mut self, description: impl Into<String>) -> Self {
78        self.description = description.into();
79        self
80    }
81
82    pub fn streaming(mut self) -> Self {
83        self.streaming = true;
84        self
85    }
86}
87
88/// Description of a node kind.
89///
90/// Unknown keys are rejected: a misspelled `config_schema` or `handles` in a
91/// plugin manifest would otherwise silently change how the node behaves.
92#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct NodeDescriptor {
95    /// Node `type` used in workflow documents.
96    pub kind: String,
97    pub title: String,
98    #[serde(default, skip_serializing_if = "String::is_empty")]
99    pub description: String,
100    #[serde(default)]
101    pub category: NodeCategory,
102    /// JSON Schema of the node's config object (the node fields other than
103    /// id/type/title/parent/policy). `{}` when unspecified.
104    #[serde(default = "empty_schema")]
105    pub config_schema: serde_json::Value,
106    /// Static outputs. Nodes whose outputs depend on config (start, end, code...)
107    /// list none and set `dynamic_outputs`.
108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
109    pub outputs: Vec<OutputDescriptor>,
110    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
111    pub dynamic_outputs: bool,
112    #[serde(default)]
113    pub handles: Handles,
114    /// Whether the node owns a child scope (iteration, loop).
115    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
116    pub container: bool,
117    /// Short icon hint (e.g. `brain`, `globe`, `code`), purely cosmetic.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub icon: Option<String>,
120    /// Origin: `builtin`, the crate name, or `plugin:<name>`.
121    #[serde(default, skip_serializing_if = "String::is_empty")]
122    pub source: String,
123}
124
125fn empty_schema() -> serde_json::Value {
126    serde_json::json!({})
127}
128
129impl NodeDescriptor {
130    pub fn new(kind: impl Into<String>, title: impl Into<String>, category: NodeCategory) -> Self {
131        Self {
132            kind: kind.into(),
133            title: title.into(),
134            description: String::new(),
135            category,
136            config_schema: empty_schema(),
137            outputs: Vec::new(),
138            dynamic_outputs: false,
139            handles: Handles::Single,
140            container: false,
141            icon: None,
142            source: String::new(),
143        }
144    }
145
146    pub fn describe(mut self, description: impl Into<String>) -> Self {
147        self.description = description.into();
148        self
149    }
150
151    pub fn schema(mut self, schema: serde_json::Value) -> Self {
152        self.config_schema = schema;
153        self
154    }
155
156    pub fn output(mut self, output: OutputDescriptor) -> Self {
157        self.outputs.push(output);
158        self
159    }
160
161    pub fn dynamic_outputs(mut self) -> Self {
162        self.dynamic_outputs = true;
163        self
164    }
165
166    pub fn handles(mut self, handles: Handles) -> Self {
167        self.handles = handles;
168        self
169    }
170
171    pub fn container(mut self) -> Self {
172        self.container = true;
173        self
174    }
175
176    pub fn icon(mut self, icon: impl Into<String>) -> Self {
177        self.icon = Some(icon.into());
178        self
179    }
180
181    pub fn source(mut self, source: impl Into<String>) -> Self {
182        self.source = source.into();
183        self
184    }
185
186    /// Minimal descriptor used for kinds registered without one.
187    pub fn bare(kind: &str) -> Self {
188        Self::new(kind, kind, NodeCategory::Other)
189    }
190
191    /// Whether this is a bare (placeholder) descriptor without real metadata.
192    pub fn is_bare(&self) -> bool {
193        self.title == self.kind && self.description.is_empty() && self.source.is_empty()
194    }
195}
196
197/// Reusable JSON Schema fragments for node config schemas.
198pub mod schema {
199    use serde_json::{Value, json};
200
201    /// Draft used by every config schema.
202    pub const DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";
203
204    /// Top-level config schema with `properties` and `required`. The schema is
205    /// closed (`additionalProperties: false`): workflow validation reports any
206    /// other key as an unknown field. Builder metadata belongs in `x-` keys,
207    /// which are stripped before configs are checked. Use [`open_object`] for
208    /// configs that legitimately take arbitrary keys.
209    pub fn object(properties: Value, required: &[&str]) -> Value {
210        json!({
211            "$schema": DRAFT,
212            "type": "object",
213            "properties": properties,
214            "required": required,
215            "additionalProperties": false
216        })
217    }
218
219    /// Like [`object`], but other keys are allowed and not reported.
220    pub fn open_object(properties: Value, required: &[&str]) -> Value {
221        json!({ "$schema": DRAFT, "type": "object", "properties": properties, "required": required })
222    }
223
224    /// A deprecated alias of `replacement`, accepted with a warning.
225    pub fn deprecated_alias(schema: Value, replacement: &str) -> Value {
226        let mut schema = schema;
227        if let Value::Object(map) = &mut schema {
228            map.insert("deprecated".into(), Value::Bool(true));
229            map.insert("description".into(), Value::String(format!("Deprecated alias of `{replacement}`")));
230        }
231        schema
232    }
233
234    /// Nested object schema (no `$schema` key).
235    pub fn nested(properties: Value, required: &[&str]) -> Value {
236        json!({ "type": "object", "properties": properties, "required": required })
237    }
238
239    /// A variable selector: `["namespace", "name", ...]` or `"namespace.name"`.
240    pub fn selector() -> Value {
241        json!({
242            "description": "Variable selector: [namespace, name, path...] or \"namespace.name\"",
243            "oneOf": [
244                { "type": "array", "items": { "type": "string", "minLength": 1 }, "minItems": 2 },
245                { "type": "string", "pattern": "^[^.\\s]+(\\.[^.\\s]+)+$" }
246            ]
247        })
248    }
249
250    /// A text template that may contain `{{#namespace.name#}}` placeholders.
251    pub fn template(description: &str) -> Value {
252        json!({ "type": "string", "description": description })
253    }
254
255    /// Declared value type names (including form-field aliases).
256    pub fn value_type() -> Value {
257        json!({
258            "type": "string",
259            "enum": [
260                "any", "none", "string", "secret", "number", "integer", "float", "boolean", "object", "file",
261                "array[any]", "array[string]", "array[number]", "array[boolean]", "array[object]", "array[file]",
262                "array", "file-list", "json", "text-input", "paragraph", "select", "checkbox"
263            ]
264        })
265    }
266
267    /// `and` / `or`.
268    pub fn logical_operator() -> Value {
269        json!({ "type": "string", "enum": ["and", "or"], "default": "and" })
270    }
271
272    /// Comparison operator names (canonical spellings and ASCII aliases).
273    pub fn comparison_operator() -> Value {
274        json!({
275            "type": "string",
276            "enum": [
277                "contains", "not contains", "start with", "starts with", "start_with", "starts_with",
278                "end with", "ends with", "end_with", "ends_with", "is", "is not", "is_not",
279                "empty", "not empty", "not_empty", "in", "not in", "not_in", "all of", "all_of",
280                "=", "==", "eq", "≠", "!=", "ne", ">", "gt", "<", "lt", "≥", ">=", "ge", "≤", "<=", "le",
281                "null", "is null", "not null", "is not null", "not_null", "exists", "not exists", "not_exists"
282            ]
283        })
284    }
285
286    /// Condition on an attribute (`key`) of list items or files.
287    pub fn key_condition() -> Value {
288        nested(
289            json!({
290                "key": { "type": "string" },
291                "comparison_operator": comparison_operator(),
292                "value": {}
293            }),
294            &["comparison_operator"],
295        )
296    }
297
298    /// One condition: `{variable_selector, comparison_operator, value, sub_variable_condition}`.
299    pub fn condition() -> Value {
300        nested(
301            json!({
302                "variable_selector": selector(),
303                "comparison_operator": comparison_operator(),
304                "value": { "description": "Right-hand side; strings may contain placeholders" },
305                "sub_variable_condition": nested(
306                    json!({
307                        "logical_operator": logical_operator(),
308                        "conditions": { "type": "array", "items": key_condition() }
309                    }),
310                    &[]
311                )
312            }),
313            &["variable_selector", "comparison_operator"],
314        )
315    }
316
317    /// Array of [`condition`]s.
318    pub fn conditions() -> Value {
319        json!({ "type": "array", "items": condition() })
320    }
321
322    /// `[{variable, value_selector}]` bindings.
323    pub fn variable_bindings() -> Value {
324        json!({
325            "type": "array",
326            "items": closed(nested(
327                json!({ "variable": { "type": "string", "minLength": 1 }, "value_selector": selector() }),
328                &["variable", "value_selector"]
329            ))
330        })
331    }
332
333    /// `schema` with `additionalProperties: false`.
334    pub fn closed(schema: Value) -> Value {
335        let mut schema = schema;
336        if let Value::Object(map) = &mut schema {
337            map.insert("additionalProperties".into(), Value::Bool(false));
338        }
339        schema
340    }
341
342    /// Model reference used by model-backed nodes.
343    pub fn model() -> Value {
344        nested(
345            json!({
346                "provider": { "type": "string", "minLength": 1 },
347                "name": { "type": "string", "minLength": 1 },
348                "mode": { "type": "string", "enum": ["chat", "completion"] },
349                "completion_params": { "type": "object" }
350            }),
351            &["provider", "name"],
352        )
353    }
354}