Skip to main content

subspace_agent_tools/
schema.rs

1//! JSON schemas for `action`-tagged tools.
2//!
3//! Model APIs accept a flat object schema for function parameters; a top-level
4//! `oneOf` is dropped or collapsed to one variant, which hid every action but
5//! the last from the model. So each schema is one object: an `action` enum, every
6//! field as an optional property, and the required fields per action in the
7//! descriptions. The Rust enums that decode the call stay strict.
8
9use super::{Arguments, MAX_BATCH};
10use serde_json::{Map, Value, json};
11
12/// One action: its name, what it does, and its fields as (name, schema, required).
13#[derive(Clone, Debug)]
14pub struct Action {
15    pub(crate) name: &'static str,
16    purpose: &'static str,
17    fields: Vec<(&'static str, Value, bool)>,
18}
19
20/// One field of a non-action tool.
21#[derive(Clone, Debug)]
22pub struct Field {
23    name: &'static str,
24    schema: Value,
25    required: bool,
26}
27
28pub fn action(
29    name: &'static str,
30    purpose: &'static str,
31    fields: Vec<(&'static str, Value, bool)>,
32) -> Action {
33    Action {
34        name,
35        purpose,
36        fields,
37    }
38}
39
40pub fn field(name: &'static str, schema: Value, required: bool) -> Field {
41    Field {
42        name,
43        schema,
44        required,
45    }
46}
47
48/// "ado_query (query; optional limit): Run WIQL." for the action description.
49fn usage(action: &Action) -> String {
50    let names = |required: bool| -> Vec<&str> {
51        action
52            .fields
53            .iter()
54            .filter(|(_, _, needed)| *needed == required)
55            .map(|(name, _, _)| *name)
56            .collect()
57    };
58    let (required, optional) = (names(true), names(false));
59    let mut parts = Vec::new();
60    if !required.is_empty() {
61        parts.push(required.join(", "));
62    }
63    if !optional.is_empty() {
64        parts.push(format!("optional {}", optional.join(", ")));
65    }
66    let fields = if parts.is_empty() {
67        String::new()
68    } else {
69        format!(" ({})", parts.join("; "))
70    };
71    format!("{}{fields}: {}", action.name, action.purpose)
72}
73
74/// One flat object schema over `actions`: the arguments of a read tool, or
75/// one operation of a write tool.
76pub fn flat(actions: &[Action]) -> Arguments {
77    Arguments::Actions {
78        actions: actions.to_vec(),
79        batched: false,
80    }
81}
82
83pub(crate) fn flat_schema(actions: &[Action]) -> Value {
84    let names: Vec<&str> = actions.iter().map(|action| action.name).collect();
85    let guide: Vec<String> = actions.iter().map(usage).collect();
86    let mut properties = Map::new();
87    properties.insert(
88        "action".into(),
89        json!({"type":"string","enum":names,"description":guide.join("\n")}),
90    );
91    for (name, schema, _) in actions.iter().flat_map(|action| &action.fields) {
92        let merged = merge(properties.remove(*name), schema);
93        properties.insert((*name).into(), merged);
94    }
95    json!({"type":"object","additionalProperties":false,"required":["action"],"properties":properties})
96}
97
98/// The arguments of a write tool: 1 to 20 operations over `actions`.
99pub fn batch(actions: &[Action]) -> Arguments {
100    Arguments::Actions {
101        actions: actions.to_vec(),
102        batched: true,
103    }
104}
105
106pub fn single(fields: Vec<Field>) -> Arguments {
107    Arguments::Single { fields }
108}
109
110pub(crate) fn actions_schema(actions: &[Action], batched: bool) -> Value {
111    if batched {
112        let mut operations =
113            json!({"type":"array","maxItems":MAX_BATCH,"items":flat_schema(actions)});
114        operations["minItems"] = json!(1);
115        json!({"type":"object","additionalProperties":false,"required":["operations"],"properties":{"operations":operations}})
116    } else {
117        flat_schema(actions)
118    }
119}
120
121pub(crate) fn single_schema(fields: &[Field]) -> Value {
122    let properties: Map<String, Value> = fields
123        .iter()
124        .map(|field| (field.name.into(), field.schema.clone()))
125        .collect();
126    let required: Vec<&str> = fields
127        .iter()
128        .filter(|field| field.required)
129        .map(|field| field.name)
130        .collect();
131    let mut schema = json!({
132        "type":"object",
133        "additionalProperties":false,
134        "properties":properties,
135    });
136    if !required.is_empty() {
137        schema["required"] = json!(required);
138    }
139    schema
140}
141
142/// The same field name can mean different things per action, such as a
143/// numeric `id` and a text `id`; the property then accepts either.
144fn merge(existing: Option<Value>, schema: &Value) -> Value {
145    match existing {
146        None => schema.clone(),
147        Some(known) if known == *schema => known,
148        Some(known) => {
149            let mut options = match known.get("anyOf").and_then(Value::as_array) {
150                Some(options) => options.clone(),
151                None => vec![known],
152            };
153            if !options.contains(schema) {
154                options.push(schema.clone());
155            }
156            json!({ "anyOf": options })
157        }
158    }
159}
160
161pub fn text() -> Value {
162    json!({"type":"string"})
163}
164
165pub fn id() -> Value {
166    json!({"type":"integer","minimum":1})
167}
168
169/// A comment or description body.
170pub fn body() -> Value {
171    json!({"type":"string","maxLength":65536})
172}
173
174#[cfg(test)]
175mod tests {
176    use super::{action, batch, field, flat, id, single, text};
177    use serde_json::{Value, json};
178
179    #[test]
180    fn schemas_are_flat_objects_that_list_every_action_and_merge_field_types() {
181        let schema = flat(&[
182            action(
183                "item",
184                "One item.",
185                vec![("id", id(), true), ("page", id(), false)],
186            ),
187            action("risk", "One risk.", vec![("id", text(), true)]),
188            action("scope", "Boundaries.", vec![]),
189        ])
190        .input_schema();
191        assert!(schema.get("oneOf").is_none(), "no top-level oneOf");
192        assert_eq!(schema["additionalProperties"], false);
193        assert_eq!(
194            schema["properties"]["action"]["enum"],
195            json!(["item", "risk", "scope"])
196        );
197        let id_types: Vec<&Value> = schema["properties"]["id"]["anyOf"]
198            .as_array()
199            .unwrap()
200            .iter()
201            .map(|option| &option["type"])
202            .collect();
203        assert_eq!(id_types, ["integer", "string"]);
204        let guide = schema["properties"]["action"]["description"]
205            .as_str()
206            .unwrap();
207        assert!(guide.contains("item (id; optional page): One item."));
208        assert!(guide.contains("scope: Boundaries."));
209        let write =
210            batch(&[action("note", "A note.", vec![("body", text(), true)])]).input_schema();
211        assert_eq!(write["properties"]["operations"]["maxItems"], 20);
212        assert_eq!(write["required"], json!(["operations"]));
213        assert_eq!(write["properties"]["operations"]["minItems"], 1);
214        let single = single(vec![field("query", text(), true)]).input_schema();
215        assert_eq!(
216            single,
217            json!({"type":"object","additionalProperties":false,"required":["query"],"properties":{"query":{"type":"string"}}})
218        );
219    }
220}