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`. Additional
205    /// properties are allowed because documents may carry builder-only metadata.
206    pub fn object(properties: Value, required: &[&str]) -> Value {
207        json!({ "$schema": DRAFT, "type": "object", "properties": properties, "required": required })
208    }
209
210    /// Nested object schema (no `$schema` key).
211    pub fn nested(properties: Value, required: &[&str]) -> Value {
212        json!({ "type": "object", "properties": properties, "required": required })
213    }
214
215    /// A variable selector: `["namespace", "name", ...]` or `"namespace.name"`.
216    pub fn selector() -> Value {
217        json!({
218            "description": "Variable selector: [namespace, name, path...] or \"namespace.name\"",
219            "oneOf": [
220                { "type": "array", "items": { "type": "string", "minLength": 1 }, "minItems": 2 },
221                { "type": "string", "pattern": "^[^.\\s]+(\\.[^.\\s]+)+$" }
222            ]
223        })
224    }
225
226    /// A text template that may contain `{{#namespace.name#}}` placeholders.
227    pub fn template(description: &str) -> Value {
228        json!({ "type": "string", "description": description })
229    }
230
231    /// Declared value type names (including form-field aliases).
232    pub fn value_type() -> Value {
233        json!({
234            "type": "string",
235            "enum": [
236                "any", "none", "string", "secret", "number", "integer", "float", "boolean", "object", "file",
237                "array[any]", "array[string]", "array[number]", "array[boolean]", "array[object]", "array[file]",
238                "array", "file-list", "json", "text-input", "paragraph", "select", "checkbox"
239            ]
240        })
241    }
242
243    /// `and` / `or`.
244    pub fn logical_operator() -> Value {
245        json!({ "type": "string", "enum": ["and", "or"], "default": "and" })
246    }
247
248    /// Comparison operator names (canonical spellings and ASCII aliases).
249    pub fn comparison_operator() -> Value {
250        json!({
251            "type": "string",
252            "enum": [
253                "contains", "not contains", "start with", "starts with", "start_with", "starts_with",
254                "end with", "ends with", "end_with", "ends_with", "is", "is not", "is_not",
255                "empty", "not empty", "not_empty", "in", "not in", "not_in", "all of", "all_of",
256                "=", "==", "eq", "≠", "!=", "ne", ">", "gt", "<", "lt", "≥", ">=", "ge", "≤", "<=", "le",
257                "null", "is null", "not null", "is not null", "not_null", "exists", "not exists", "not_exists"
258            ]
259        })
260    }
261
262    /// Condition on an attribute (`key`) of list items or files.
263    pub fn key_condition() -> Value {
264        nested(
265            json!({
266                "key": { "type": "string" },
267                "comparison_operator": comparison_operator(),
268                "value": {}
269            }),
270            &["comparison_operator"],
271        )
272    }
273
274    /// One condition: `{variable_selector, comparison_operator, value, sub_variable_condition}`.
275    pub fn condition() -> Value {
276        nested(
277            json!({
278                "variable_selector": selector(),
279                "comparison_operator": comparison_operator(),
280                "value": { "description": "Right-hand side; strings may contain placeholders" },
281                "sub_variable_condition": nested(
282                    json!({
283                        "logical_operator": logical_operator(),
284                        "conditions": { "type": "array", "items": key_condition() }
285                    }),
286                    &[]
287                )
288            }),
289            &["variable_selector", "comparison_operator"],
290        )
291    }
292
293    /// Array of [`condition`]s.
294    pub fn conditions() -> Value {
295        json!({ "type": "array", "items": condition() })
296    }
297
298    /// `[{variable, value_selector}]` bindings.
299    pub fn variable_bindings() -> Value {
300        json!({
301            "type": "array",
302            "items": nested(
303                json!({ "variable": { "type": "string", "minLength": 1 }, "value_selector": selector() }),
304                &["variable", "value_selector"]
305            )
306        })
307    }
308
309    /// Model reference used by model-backed nodes.
310    pub fn model() -> Value {
311        nested(
312            json!({
313                "provider": { "type": "string", "minLength": 1 },
314                "name": { "type": "string", "minLength": 1 },
315                "mode": { "type": "string", "enum": ["chat", "completion"] },
316                "completion_params": { "type": "object" }
317            }),
318            &["provider", "name"],
319        )
320    }
321}