1use std::collections::HashMap;
20use std::sync::Arc;
21
22use gadk_genai::Schema;
23
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
26pub enum Mode {
27 #[default]
29 Unset,
30 Chat,
32 Task,
34 SingleTurn,
36}
37
38impl Mode {
39 pub fn as_str(&self) -> &'static str {
41 match self {
42 Mode::Unset => "",
43 Mode::Chat => "chat",
44 Mode::Task => "task",
45 Mode::SingleTurn => "single_turn",
46 }
47 }
48}
49
50#[derive(Debug, Clone, Default)]
53pub struct BoundModes {
54 map: Arc<HashMap<(String, usize), Mode>>,
55 output_schemas: Arc<HashMap<(String, usize), Option<Schema>>>,
56}
57
58impl BoundModes {
59 pub fn with(&self, agent_name: &str, state_key: usize, mode: Mode) -> Self {
62 if mode == Mode::Unset {
63 return self.clone();
64 }
65 let mut map = (*self.map).clone();
66 map.insert((agent_name.to_string(), state_key), mode);
67 Self {
68 map: Arc::new(map),
69 output_schemas: Arc::clone(&self.output_schemas),
70 }
71 }
72
73 pub fn get(&self, agent_name: &str, state_key: usize) -> Option<Mode> {
75 self.map.get(&(agent_name.to_string(), state_key)).copied()
76 }
77
78 pub fn with_output_schema(
81 &self,
82 agent_name: &str,
83 state_key: usize,
84 schema: Option<Schema>,
85 ) -> Self {
86 let mut output_schemas = (*self.output_schemas).clone();
87 output_schemas.insert((agent_name.to_string(), state_key), schema);
88 Self {
89 map: Arc::clone(&self.map),
90 output_schemas: Arc::new(output_schemas),
91 }
92 }
93
94 pub fn output_schema(&self, agent_name: &str, state_key: usize) -> Option<Option<&Schema>> {
97 self.output_schemas
98 .get(&(agent_name.to_string(), state_key))
99 .map(Option::as_ref)
100 }
101}
102
103#[cfg(test)]
104#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
105mod tests {
106 use super::*;
107
108 fn object(prop: &str) -> Schema {
109 serde_json::from_value(serde_json::json!({
110 "type": "OBJECT",
111 "properties": {prop: {"type": "STRING"}}
112 }))
113 .unwrap()
114 }
115
116 #[test]
117 fn output_schema_binding_is_keyed_shadowable_and_kept_by_mode_bindings() {
118 let outer = BoundModes::default().with_output_schema("a", 1, Some(object("x")));
119 assert_eq!(outer.output_schema("a", 1), Some(Some(&object("x"))));
120 assert_eq!(outer.output_schema("a", 2), None, "another state");
121 assert_eq!(outer.output_schema("b", 1), None, "another name");
122 let both = outer.with("a", 1, Mode::SingleTurn);
124 assert_eq!(both.output_schema("a", 1), Some(Some(&object("x"))));
125 assert_eq!(both.get("a", 1), Some(Mode::SingleTurn));
126 let inner = both.with_output_schema("a", 1, None);
128 assert_eq!(inner.output_schema("a", 1), Some(None));
129 assert_eq!(inner.get("a", 1), Some(Mode::SingleTurn));
130 assert_eq!(both.output_schema("a", 1), Some(Some(&object("x"))));
131 }
132}