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