Skip to main content

nenjo_tool_api/
async_ops.rs

1//! Shared contracts for model-visible async operation tools.
2//!
3//! Runtime crates own operation scheduling, cancellation, polling, and event
4//! delivery. This module only defines stable tool names, argument DTOs, JSON
5//! schemas, and operation lifecycle enums.
6
7use serde::{Deserialize, Deserializer, Serialize};
8use serde_json::json;
9
10pub const WAIT_OPERATIONS_TOOL_NAME: &str = "wait_operations";
11pub const INSPECT_OPERATIONS_TOOL_NAME: &str = "inspect_operations";
12pub const STOP_OPERATIONS_TOOL_NAME: &str = "stop_operations";
13pub const SEND_OPERATION_INPUT_TOOL_NAME: &str = "send_operation_input";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum AsyncOperationKind {
18    Ability,
19    Delegation,
20    SubAgent,
21    Shell,
22    Media,
23    TaskExecution,
24}
25
26impl AsyncOperationKind {
27    pub fn as_str(self) -> &'static str {
28        match self {
29            Self::Ability => "ability",
30            Self::Delegation => "delegation",
31            Self::SubAgent => "sub_agent",
32            Self::Shell => "shell",
33            Self::Media => "media",
34            Self::TaskExecution => "task_execution",
35        }
36    }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum AsyncOperationStatus {
42    Running,
43    WaitingForInput,
44    Completed,
45    Failed,
46    Stopped,
47}
48
49impl AsyncOperationStatus {
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Running => "running",
53            Self::WaitingForInput => "waiting_for_input",
54            Self::Completed => "completed",
55            Self::Failed => "failed",
56            Self::Stopped => "stopped",
57        }
58    }
59
60    pub fn can_receive_input(self) -> bool {
61        matches!(self, Self::Running | Self::WaitingForInput)
62    }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum AsyncOperationSignalKind {
68    Started,
69    Progress,
70    NeedsInput,
71    Completed,
72    Failed,
73    Stopped,
74}
75
76impl AsyncOperationSignalKind {
77    pub fn as_str(self) -> &'static str {
78        match self {
79            Self::Started => "started",
80            Self::Progress => "progress",
81            Self::NeedsInput => "needs_input",
82            Self::Completed => "completed",
83            Self::Failed => "failed",
84            Self::Stopped => "stopped",
85        }
86    }
87}
88
89#[derive(Debug, Clone, Deserialize)]
90pub struct InspectOperationsArgs {
91    #[serde(default)]
92    pub operations: Vec<String>,
93    #[serde(default)]
94    pub kind: Option<AsyncOperationKind>,
95    #[serde(default)]
96    pub include_transcript: bool,
97    #[serde(
98        default = "default_inspect_limit",
99        deserialize_with = "deserialize_usize_from_json_number"
100    )]
101    pub limit: usize,
102}
103
104#[derive(Debug, Clone, Deserialize)]
105pub struct StopOperationsArgs {
106    #[serde(default)]
107    pub operations: Vec<String>,
108    #[serde(default)]
109    pub kind: Option<AsyncOperationKind>,
110    pub reason: Option<String>,
111}
112
113#[derive(Debug, Clone, Deserialize)]
114pub struct WaitOperationsArgs {
115    #[serde(
116        default = "default_wait_seconds",
117        deserialize_with = "deserialize_u64_from_json_number"
118    )]
119    pub seconds: u64,
120    #[serde(default)]
121    pub kind: Option<AsyncOperationKind>,
122    pub reason: Option<String>,
123}
124
125#[derive(Debug, Clone, Deserialize)]
126pub struct SendOperationInputArgs {
127    #[serde(default)]
128    pub operations: Vec<String>,
129    pub message: String,
130}
131
132pub fn inspect_operations_parameters_schema() -> serde_json::Value {
133    json!({
134        "type": "object",
135        "properties": {
136            "operations": {"type": "array", "items": {"type": "string"}},
137            "kind": operation_kind_schema(),
138            "include_transcript": {"type": "boolean"},
139            "limit": {"type": "integer", "minimum": 1, "maximum": 50}
140        },
141        "additionalProperties": false
142    })
143}
144
145pub fn stop_operations_parameters_schema() -> serde_json::Value {
146    json!({
147        "type": "object",
148        "properties": {
149            "operations": {"type": "array", "items": {"type": "string"}},
150            "kind": operation_kind_schema(),
151            "reason": {"type": "string"}
152        },
153        "additionalProperties": false
154    })
155}
156
157pub fn wait_operations_parameters_schema() -> serde_json::Value {
158    json!({
159        "type": "object",
160        "properties": {
161            "seconds": {"type": "integer", "minimum": 1, "maximum": 30},
162            "kind": operation_kind_schema(),
163            "reason": {"type": "string"}
164        },
165        "additionalProperties": false
166    })
167}
168
169pub fn send_operation_input_parameters_schema() -> serde_json::Value {
170    json!({
171        "type": "object",
172        "properties": {
173            "operations": {"type": "array", "items": {"type": "string"}},
174            "message": {"type": "string"}
175        },
176        "required": ["operations", "message"],
177        "additionalProperties": false
178    })
179}
180
181pub fn operation_kind_schema() -> serde_json::Value {
182    json!({
183        "type": "string",
184        "enum": ["ability", "delegation", "sub_agent", "shell", "media", "task_execution"]
185    })
186}
187
188fn default_inspect_limit() -> usize {
189    30
190}
191
192pub fn deserialize_usize_from_json_number<'de, D>(deserializer: D) -> Result<usize, D::Error>
193where
194    D: Deserializer<'de>,
195{
196    let value = serde_json::Value::deserialize(deserializer)?;
197    match value {
198        serde_json::Value::Number(number) => {
199            if let Some(raw) = number.as_u64() {
200                usize::try_from(raw).map_err(serde::de::Error::custom)
201            } else if let Some(raw) = number.as_f64() {
202                if raw.is_finite() && raw.fract() == 0.0 && raw >= 0.0 {
203                    usize::try_from(raw as u64).map_err(serde::de::Error::custom)
204                } else {
205                    Err(serde::de::Error::custom(
206                        "expected a non-negative whole number",
207                    ))
208                }
209            } else {
210                Err(serde::de::Error::custom(
211                    "expected a non-negative whole number",
212                ))
213            }
214        }
215        other => Err(serde::de::Error::custom(format!(
216            "expected a non-negative whole number, got {other}"
217        ))),
218    }
219}
220
221pub fn deserialize_u64_from_json_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
222where
223    D: Deserializer<'de>,
224{
225    let value = serde_json::Value::deserialize(deserializer)?;
226    match value {
227        serde_json::Value::Number(number) => {
228            if let Some(raw) = number.as_u64() {
229                Ok(raw)
230            } else if let Some(raw) = number.as_f64() {
231                if raw.is_finite() && raw.fract() == 0.0 && raw >= 0.0 {
232                    Ok(raw as u64)
233                } else {
234                    Err(serde::de::Error::custom(
235                        "expected a non-negative whole number",
236                    ))
237                }
238            } else {
239                Err(serde::de::Error::custom(
240                    "expected a non-negative whole number",
241                ))
242            }
243        }
244        other => Err(serde::de::Error::custom(format!(
245            "expected a non-negative whole number, got {other}"
246        ))),
247    }
248}
249
250fn default_wait_seconds() -> u64 {
251    10
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn async_operation_kind_uses_wire_names() {
260        assert_eq!(AsyncOperationKind::Ability.as_str(), "ability");
261        assert_eq!(AsyncOperationKind::Delegation.as_str(), "delegation");
262        assert_eq!(AsyncOperationKind::SubAgent.as_str(), "sub_agent");
263        assert_eq!(AsyncOperationKind::Shell.as_str(), "shell");
264        assert_eq!(AsyncOperationKind::Media.as_str(), "media");
265        assert_eq!(AsyncOperationKind::TaskExecution.as_str(), "task_execution");
266    }
267
268    #[test]
269    fn wait_args_deserialize_with_defaults() {
270        let args: WaitOperationsArgs = serde_json::from_value(json!({})).unwrap();
271
272        assert_eq!(args.seconds, 10);
273        assert_eq!(args.kind, None);
274    }
275
276    #[test]
277    fn wait_args_accept_whole_float_seconds_from_model_args() {
278        let args: WaitOperationsArgs = serde_json::from_value(json!({
279            "kind": "ability",
280            "seconds": 30.0
281        }))
282        .unwrap();
283
284        assert_eq!(args.seconds, 30);
285        assert_eq!(args.kind, Some(AsyncOperationKind::Ability));
286    }
287
288    #[test]
289    fn wait_args_reject_fractional_seconds() {
290        let err = serde_json::from_value::<WaitOperationsArgs>(json!({
291            "seconds": 5.5
292        }))
293        .unwrap_err();
294
295        assert!(err.to_string().contains("whole number"));
296    }
297
298    #[test]
299    fn inspect_args_accept_whole_float_limit_from_model_args() {
300        let args: InspectOperationsArgs = serde_json::from_value(json!({
301            "operations": ["ability_build_agent_2"],
302            "include_transcript": true,
303            "limit": 5.0
304        }))
305        .unwrap();
306
307        assert_eq!(args.limit, 5);
308    }
309
310    #[test]
311    fn inspect_args_reject_fractional_limit() {
312        let err = serde_json::from_value::<InspectOperationsArgs>(json!({
313            "limit": 5.5
314        }))
315        .unwrap_err();
316
317        assert!(err.to_string().contains("whole number"));
318    }
319}