1use serde_json::{Map, Value, json};
15
16use crate::catalog::NodeDescriptor;
17use crate::catalog::schema::{DRAFT, selector, value_type};
18
19pub const SCHEMA_ID: &str = "https://raw.githubusercontent.com/Graphrt/graphrt/main/schema/workflow-v1.schema.json";
21
22pub fn workflow_schema(descriptors: &[NodeDescriptor]) -> Value {
24 let mut defs = Map::new();
25 defs.insert("selector".into(), selector());
26 defs.insert("variable".into(), variable_def());
27 defs.insert("retry".into(), retry_def());
28 defs.insert("on_error".into(), on_error_def());
29 defs.insert("edge".into(), edge_def());
30 let mut branches = Vec::with_capacity(descriptors.len());
31 for descriptor in descriptors {
32 let name = format!("node:{}", descriptor.kind);
33 branches.push(json!({ "$ref": format!("#/$defs/{name}") }));
34 defs.insert(name, node_def(descriptor));
35 }
36 defs.insert(
37 "node".into(),
38 json!({
39 "description": "A node; `type` selects the node kind and its config fields",
40 "type": "object",
41 "required": ["id", "type"],
42 "properties": { "type": { "enum": descriptors.iter().map(|d| d.kind.as_str()).collect::<Vec<_>>() } },
43 "oneOf": branches
44 }),
45 );
46 let decls = json!({ "type": "array", "items": { "$ref": "#/$defs/variable" } });
47 json!({
48 "$schema": DRAFT,
49 "$id": SCHEMA_ID,
50 "title": "graphrt workflow document (format version 1)",
51 "description": "A graphrt workflow. Keys starting with `x-` are free for tools and ignored by the runtime.",
52 "type": "object",
53 "required": ["graph"],
54 "properties": {
55 "version": {
56 "description": "Document format version. Omitted means \"1\".",
57 "enum": ["1", 1]
58 },
59 "name": { "type": "string" },
60 "description": { "type": "string" },
61 "env": {
62 "description": "Environment variables, read as {{#env.NAME#}}",
63 "type": "array", "items": { "$ref": "#/$defs/variable" }
64 },
65 "conversation": {
66 "description": "Conversation variables, read as {{#conversation.NAME#}}",
67 "type": "array", "items": { "$ref": "#/$defs/variable" }
68 },
69 "environment_variables": deprecated(decls.clone(), "env"),
70 "conversation_variables": deprecated(decls, "conversation"),
71 "graph": {
72 "type": "object",
73 "required": ["nodes"],
74 "properties": {
75 "nodes": { "type": "array", "items": { "$ref": "#/$defs/node" } },
76 "edges": { "type": "array", "items": { "$ref": "#/$defs/edge" } }
77 },
78 "patternProperties": extension_keys(),
79 "additionalProperties": false
80 }
81 },
82 "patternProperties": extension_keys(),
83 "additionalProperties": false,
84 "$defs": defs
85 })
86}
87
88fn extension_keys() -> Value {
89 json!({ "^x-": { "description": "Extension data for tools; ignored by the runtime" } })
90}
91
92fn deprecated(schema: Value, replacement: &str) -> Value {
93 crate::catalog::schema::deprecated_alias(schema, replacement)
94}
95
96fn variable_def() -> Value {
97 json!({
98 "type": "object",
99 "required": ["name"],
100 "properties": {
101 "name": { "type": "string", "minLength": 1 },
102 "type": value_type(),
103 "value": { "description": "Default value; omit to have the host supply it" },
104 "description": { "type": "string" },
105 "value_type": deprecated(value_type(), "type")
106 },
107 "patternProperties": extension_keys(),
108 "additionalProperties": false
109 })
110}
111
112fn retry_def() -> Value {
113 json!({
114 "description": "Retries of retryable errors; applies to every node kind",
115 "type": "object",
116 "properties": {
117 "max_retries": { "type": "integer", "minimum": 0, "default": 0 },
118 "interval_ms": { "type": "integer", "minimum": 0, "default": 0, "description": "Delay before the first retry" },
119 "backoff": { "type": "number", "minimum": 1, "default": 1, "description": "Delay multiplier per retry" }
120 },
121 "additionalProperties": false
122 })
123}
124
125fn on_error_def() -> Value {
126 json!({
127 "description": "What happens when the node fails after its retries",
128 "type": "object",
129 "required": ["strategy"],
130 "properties": {
131 "strategy": { "enum": ["fail", "fail-branch", "default-value"] },
132 "values": { "type": "object", "description": "Outputs used with `default-value`" }
133 },
134 "additionalProperties": false
135 })
136}
137
138fn edge_def() -> Value {
139 json!({
140 "type": "object",
141 "required": ["source", "target"],
142 "properties": {
143 "id": { "type": "string", "minLength": 1 },
144 "source": { "type": "string", "minLength": 1, "description": "Source node id" },
145 "target": { "type": "string", "minLength": 1, "description": "Target node id" },
146 "handle": {
147 "type": "string",
148 "default": "source",
149 "description": "Branch of the source node: `source`, `fail-branch`, or a branch node's handle (case id, class id, action id...)"
150 },
151 "sourceHandle": deprecated(json!({ "type": "string" }), "handle"),
152 "source_handle": deprecated(json!({ "type": "string" }), "handle")
153 },
154 "patternProperties": extension_keys(),
155 "additionalProperties": false
156 })
157}
158
159fn common_properties(kind: &str) -> Map<String, Value> {
161 let parent_alias = || deprecated(json!({ "type": "string" }), "parent");
162 let props = json!({
163 "id": {
164 "type": "string",
165 "description": "Unique node id; also the namespace of the node's outputs",
166 "pattern": "^[^.\\s]+$",
167 "not": { "enum": ["sys", "env", "conversation"] }
168 },
169 "type": { "const": kind },
170 "title": { "type": "string" },
171 "parent": { "type": "string", "description": "Owning iteration / loop node for nodes in a container body" },
172 "retry": { "$ref": "#/$defs/retry" },
173 "timeout_ms": { "type": "integer", "minimum": 0, "description": "Per-attempt timeout" },
174 "on_error": { "$ref": "#/$defs/on_error" },
175 "parentId": parent_alias(),
176 "container_id": parent_alias(),
177 "iteration_id": parent_alias(),
178 "loop_id": parent_alias(),
179 "error_strategy": deprecated(json!({ "enum": ["none", "fail", "fail-branch", "default-value"] }), "on_error"),
180 "default_value": deprecated(json!({}), "on_error"),
181 "retry_config": deprecated(json!({ "type": "object" }), "retry")
182 });
183 match props {
184 Value::Object(map) => map,
185 _ => Map::new(),
186 }
187}
188
189fn node_def(descriptor: &NodeDescriptor) -> Value {
191 let mut config = match &descriptor.config_schema {
192 Value::Object(map) => map.clone(),
193 _ => Map::new(),
194 };
195 config.remove("$schema");
196 let mut required = vec![json!("id"), json!("type")];
197 let mut def = Map::new();
198 def.insert("title".into(), json!(descriptor.title));
199 if !descriptor.description.is_empty() {
200 def.insert("description".into(), json!(descriptor.description));
201 }
202 def.insert("type".into(), json!("object"));
203 let mut properties = common_properties(&descriptor.kind);
204 let mergeable = config.keys().all(|k| {
205 matches!(k.as_str(), "type" | "properties" | "required" | "additionalProperties" | "description" | "title")
206 });
207 if mergeable {
208 if let Some(Value::Object(config_props)) = config.remove("properties") {
209 for (key, schema) in config_props {
210 properties.entry(key).or_insert(schema);
211 }
212 }
213 if let Some(Value::Array(config_required)) = config.remove("required") {
214 required.extend(config_required);
215 }
216 def.insert("properties".into(), Value::Object(properties));
217 def.insert("required".into(), Value::Array(required));
218 def.insert("patternProperties".into(), extension_keys());
219 if let Some(extra) = config.remove("additionalProperties") {
220 def.insert("additionalProperties".into(), extra);
221 }
222 } else {
223 def.insert("properties".into(), Value::Object(properties));
225 def.insert("required".into(), Value::Array(required));
226 def.insert("allOf".into(), json!([Value::Object(config)]));
227 }
228 Value::Object(def)
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 use crate::node::Registry;
235
236 #[test]
237 fn merges_node_kinds() {
238 let schema = workflow_schema(&Registry::with_builtins().descriptors());
239 let start = &schema["$defs"]["node:start"];
240 assert_eq!(start["properties"]["type"]["const"], "start");
241 assert_eq!(start["additionalProperties"], false);
242 assert!(start["properties"]["variables"].is_object());
243 assert!(start["properties"]["on_error"].is_object());
244 assert!(schema["$defs"]["node"]["oneOf"].as_array().is_some_and(|b| b.len() > 10));
245 assert!(start.get("$schema").is_none());
246 }
247
248 #[test]
249 fn open_plugin_schemas_stay_open() {
250 let d = NodeDescriptor::new("acme", "Acme", crate::catalog::NodeCategory::Other)
251 .schema(json!({"type": "object", "properties": {"x": {"type": "string"}}}));
252 let schema = workflow_schema(&[d]);
253 let node = &schema["$defs"]["node:acme"];
254 assert!(node.get("additionalProperties").is_none());
255 assert_eq!(node["properties"]["x"]["type"], "string");
256 }
257}