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 INSPECT_TOOL_NAME: &str = "inspect";
11pub const SEND_INPUT_TOOL_NAME: &str = "send_input";
12pub const STOP_TOOL_NAME: &str = "stop";
13pub const WAIT_TOOL_NAME: &str = "wait";
14
15/// A model-facing action supported by an async operation.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum AsyncControl {
19    Inspect,
20    SendInput,
21    Stop,
22    Wait,
23}
24
25/// Compact set of controls declared when an async operation starts.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct AsyncControls(u8);
28
29impl AsyncControls {
30    pub const NONE: Self = Self(0);
31
32    pub const fn new(control: AsyncControl) -> Self {
33        Self(control.mask())
34    }
35
36    pub const fn with(self, control: AsyncControl) -> Self {
37        Self(self.0 | control.mask())
38    }
39
40    pub const fn contains(self, control: AsyncControl) -> bool {
41        self.0 & control.mask() != 0
42    }
43
44    pub fn iter(self) -> impl Iterator<Item = AsyncControl> {
45        [
46            AsyncControl::Inspect,
47            AsyncControl::SendInput,
48            AsyncControl::Stop,
49            AsyncControl::Wait,
50        ]
51        .into_iter()
52        .filter(move |control| self.contains(*control))
53    }
54}
55
56impl AsyncControl {
57    pub const fn tool_name(self) -> &'static str {
58        match self {
59            Self::Inspect => INSPECT_TOOL_NAME,
60            Self::SendInput => SEND_INPUT_TOOL_NAME,
61            Self::Stop => STOP_TOOL_NAME,
62            Self::Wait => WAIT_TOOL_NAME,
63        }
64    }
65
66    const fn mask(self) -> u8 {
67        match self {
68            Self::Inspect => 1 << 0,
69            Self::SendInput => 1 << 1,
70            Self::Stop => 1 << 2,
71            Self::Wait => 1 << 3,
72        }
73    }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum AsyncOperationKind {
79    Ability,
80    Delegation,
81    SubAgent,
82    Shell,
83    Media,
84    TaskExecution,
85}
86
87impl AsyncOperationKind {
88    pub fn as_str(self) -> &'static str {
89        match self {
90            Self::Ability => "ability",
91            Self::Delegation => "delegation",
92            Self::SubAgent => "sub_agent",
93            Self::Shell => "shell",
94            Self::Media => "media",
95            Self::TaskExecution => "task_execution",
96        }
97    }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum AsyncOperationStatus {
103    Running,
104    WaitingForInput,
105    Completed,
106    Failed,
107    Stopped,
108}
109
110impl AsyncOperationStatus {
111    pub fn as_str(self) -> &'static str {
112        match self {
113            Self::Running => "running",
114            Self::WaitingForInput => "waiting_for_input",
115            Self::Completed => "completed",
116            Self::Failed => "failed",
117            Self::Stopped => "stopped",
118        }
119    }
120
121    pub fn can_receive_input(self) -> bool {
122        matches!(self, Self::Running | Self::WaitingForInput)
123    }
124}
125
126/// Canonical model-facing receipt returned after an async operation starts.
127#[derive(Debug, Clone, Serialize)]
128pub struct AsyncOperationStartReceipt {
129    operation_id: String,
130    kind: AsyncOperationKind,
131    status: AsyncOperationStatus,
132    control_tools: Vec<AsyncControlGuide>,
133}
134
135#[derive(Debug, Clone, Serialize)]
136struct AsyncControlGuide {
137    control: AsyncControl,
138    tool: &'static str,
139    instruction: &'static str,
140    suggested_arguments: serde_json::Value,
141}
142
143impl AsyncOperationStartReceipt {
144    pub fn new(
145        operation_id: impl Into<String>,
146        kind: AsyncOperationKind,
147        controls: AsyncControls,
148    ) -> Self {
149        let operation_id = operation_id.into();
150        let control_tools = controls
151            .iter()
152            .map(|control| AsyncControlGuide::new(control, &operation_id, kind))
153            .collect();
154        Self {
155            operation_id,
156            kind,
157            status: AsyncOperationStatus::Running,
158            control_tools,
159        }
160    }
161}
162
163impl AsyncControlGuide {
164    fn new(control: AsyncControl, operation_id: &str, kind: AsyncOperationKind) -> Self {
165        let (instruction, suggested_arguments) = match control {
166            AsyncControl::Inspect => (
167                "Use inspect to check this operation's current state or final output. Set include_transcript=true when recent activity is needed. A nested tool error while status is running is recoverable; use wait rather than stopping and restarting the operation.",
168                json!({"operations": [operation_id]}),
169            ),
170            AsyncControl::SendInput => (
171                "Use send_input only when this operation asks the parent agent for input.",
172                json!({
173                    "operations": [operation_id],
174                    "message": "<response to the operation>"
175                }),
176            ),
177            AsyncControl::Stop => (
178                "Use stop to cancel this operation when it should no longer continue. Do not stop solely because a nested tool failed while the operation remains running.",
179                json!({"operations": [operation_id]}),
180            ),
181            AsyncControl::Wait => (
182                "Use wait while this operation is running; repeat until it completes, fails, stops, or asks for input. A recoverable_tool_error means the operation is still running and the default next action is wait.",
183                json!({"seconds": 10, "kind": kind}),
184            ),
185        };
186        Self {
187            control,
188            tool: control.tool_name(),
189            instruction,
190            suggested_arguments,
191        }
192    }
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
196#[serde(rename_all = "snake_case")]
197pub enum AsyncOperationSignalKind {
198    Started,
199    Progress,
200    RecoverableToolError,
201    NeedsInput,
202    Completed,
203    Failed,
204    Stopped,
205}
206
207impl AsyncOperationSignalKind {
208    pub fn as_str(self) -> &'static str {
209        match self {
210            Self::Started => "started",
211            Self::Progress => "progress",
212            Self::RecoverableToolError => "recoverable_tool_error",
213            Self::NeedsInput => "needs_input",
214            Self::Completed => "completed",
215            Self::Failed => "failed",
216            Self::Stopped => "stopped",
217        }
218    }
219}
220
221#[derive(Debug, Clone, Deserialize)]
222pub struct InspectOperationsArgs {
223    #[serde(default, deserialize_with = "deserialize_operation_ids")]
224    pub operations: Vec<String>,
225    #[serde(default)]
226    pub kind: Option<AsyncOperationKind>,
227    #[serde(default, deserialize_with = "deserialize_bool_or_string")]
228    pub include_transcript: bool,
229    #[serde(
230        default = "default_inspect_limit",
231        deserialize_with = "deserialize_usize_from_json_number"
232    )]
233    pub limit: usize,
234}
235
236#[derive(Debug, Clone, Deserialize)]
237pub struct StopOperationsArgs {
238    #[serde(default, deserialize_with = "deserialize_operation_ids")]
239    pub operations: Vec<String>,
240    #[serde(default)]
241    pub kind: Option<AsyncOperationKind>,
242    pub reason: Option<String>,
243}
244
245#[derive(Debug, Clone, Deserialize)]
246pub struct WaitOperationsArgs {
247    #[serde(
248        default = "default_wait_seconds",
249        deserialize_with = "deserialize_u64_from_json_number"
250    )]
251    pub seconds: u64,
252    #[serde(default)]
253    pub kind: Option<AsyncOperationKind>,
254    pub reason: Option<String>,
255}
256
257#[derive(Debug, Clone, Deserialize)]
258pub struct SendOperationInputArgs {
259    #[serde(default, deserialize_with = "deserialize_operation_ids")]
260    pub operations: Vec<String>,
261    pub message: String,
262}
263
264pub fn inspect_operations_parameters_schema() -> serde_json::Value {
265    json!({
266        "type": "object",
267        "properties": {
268            "operations": {"type": "array", "items": {"type": "string"}},
269            "kind": operation_kind_schema(),
270            "include_transcript": {"type": "boolean"},
271            "limit": {"type": "integer", "minimum": 1, "maximum": 50}
272        },
273        "additionalProperties": false
274    })
275}
276
277pub fn stop_operations_parameters_schema() -> serde_json::Value {
278    json!({
279        "type": "object",
280        "properties": {
281            "operations": {"type": "array", "items": {"type": "string"}},
282            "kind": operation_kind_schema(),
283            "reason": {"type": "string"}
284        },
285        "additionalProperties": false
286    })
287}
288
289pub fn wait_operations_parameters_schema() -> serde_json::Value {
290    json!({
291        "type": "object",
292        "properties": {
293            "seconds": {"type": "integer", "minimum": 1, "maximum": 30},
294            "kind": operation_kind_schema(),
295            "reason": {"type": "string"}
296        },
297        "additionalProperties": false
298    })
299}
300
301pub fn send_operation_input_parameters_schema() -> serde_json::Value {
302    json!({
303        "type": "object",
304        "properties": {
305            "operations": {"type": "array", "items": {"type": "string"}},
306            "message": {"type": "string"}
307        },
308        "required": ["operations", "message"],
309        "additionalProperties": false
310    })
311}
312
313pub fn operation_kind_schema() -> serde_json::Value {
314    json!({
315        "type": "string",
316        "enum": ["ability", "delegation", "sub_agent", "shell", "media", "task_execution"]
317    })
318}
319
320fn default_inspect_limit() -> usize {
321    30
322}
323
324fn deserialize_operation_ids<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
325where
326    D: Deserializer<'de>,
327{
328    let value = serde_json::Value::deserialize(deserializer)?;
329    let array = match value {
330        serde_json::Value::Array(values) => serde_json::Value::Array(values),
331        serde_json::Value::String(encoded) => {
332            let decoded = serde_json::from_str::<serde_json::Value>(&encoded).map_err(|_| {
333                serde::de::Error::custom(
334                    "expected an array of operation ids or a JSON-encoded array",
335                )
336            })?;
337            if !decoded.is_array() {
338                return Err(serde::de::Error::custom(
339                    "expected an array of operation ids or a JSON-encoded array",
340                ));
341            }
342            decoded
343        }
344        _ => {
345            return Err(serde::de::Error::custom(
346                "expected an array of operation ids or a JSON-encoded array",
347            ));
348        }
349    };
350
351    serde_json::from_value(array).map_err(serde::de::Error::custom)
352}
353
354fn deserialize_bool_or_string<'de, D>(deserializer: D) -> Result<bool, D::Error>
355where
356    D: Deserializer<'de>,
357{
358    match serde_json::Value::deserialize(deserializer)? {
359        serde_json::Value::Bool(value) => Ok(value),
360        serde_json::Value::String(value) if value == "true" => Ok(true),
361        serde_json::Value::String(value) if value == "false" => Ok(false),
362        _ => Err(serde::de::Error::custom(
363            "expected a boolean or the string \"true\" or \"false\"",
364        )),
365    }
366}
367
368pub fn deserialize_usize_from_json_number<'de, D>(deserializer: D) -> Result<usize, D::Error>
369where
370    D: Deserializer<'de>,
371{
372    let value = serde_json::Value::deserialize(deserializer)?;
373    let number = deserialize_non_negative_whole_number(value)?;
374    usize::try_from(number).map_err(serde::de::Error::custom)
375}
376
377pub fn deserialize_u64_from_json_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
378where
379    D: Deserializer<'de>,
380{
381    let value = serde_json::Value::deserialize(deserializer)?;
382    deserialize_non_negative_whole_number(value)
383}
384
385fn deserialize_non_negative_whole_number<E>(value: serde_json::Value) -> Result<u64, E>
386where
387    E: serde::de::Error,
388{
389    match value {
390        serde_json::Value::Number(number) => {
391            if let Some(raw) = number.as_u64() {
392                Ok(raw)
393            } else if let Some(raw) = number.as_f64() {
394                // `u64::MAX as f64` rounds up to 2^64. A strict comparison is
395                // therefore required or the first out-of-range float silently
396                // saturates to `u64::MAX` during the cast.
397                if raw.is_finite() && raw.fract() == 0.0 && raw >= 0.0 && raw < u64::MAX as f64 {
398                    Ok(raw as u64)
399                } else {
400                    Err(E::custom("expected a non-negative whole number"))
401                }
402            } else {
403                Err(E::custom("expected a non-negative whole number"))
404            }
405        }
406        serde_json::Value::String(raw)
407            if !raw.is_empty() && raw.bytes().all(|byte| byte.is_ascii_digit()) =>
408        {
409            raw.parse::<u64>().map_err(E::custom)
410        }
411        other => Err(E::custom(format!(
412            "expected a non-negative whole number, got {other}"
413        ))),
414    }
415}
416
417fn default_wait_seconds() -> u64 {
418    10
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn async_controls_track_explicit_capabilities() {
427        let controls = AsyncControls::new(AsyncControl::Inspect).with(AsyncControl::Wait);
428
429        assert!(controls.contains(AsyncControl::Inspect));
430        assert!(controls.contains(AsyncControl::Wait));
431        assert!(!controls.contains(AsyncControl::SendInput));
432        assert!(!controls.contains(AsyncControl::Stop));
433    }
434
435    #[test]
436    fn recoverable_tool_error_has_a_stable_wire_name() {
437        assert_eq!(
438            AsyncOperationSignalKind::RecoverableToolError.as_str(),
439            "recoverable_tool_error"
440        );
441    }
442
443    #[test]
444    fn start_receipt_guides_recovery_without_restarting() {
445        let receipt = AsyncOperationStartReceipt::new(
446            "ability_build_routine_1",
447            AsyncOperationKind::Ability,
448            AsyncControls::new(AsyncControl::Inspect)
449                .with(AsyncControl::Stop)
450                .with(AsyncControl::Wait),
451        );
452        let value = serde_json::to_value(receipt).unwrap();
453        let instructions = value["control_tools"]
454            .as_array()
455            .unwrap()
456            .iter()
457            .filter_map(|control| control["instruction"].as_str())
458            .collect::<Vec<_>>()
459            .join(" ");
460
461        assert!(instructions.contains("recoverable"));
462        assert!(instructions.contains("Do not stop solely"));
463        assert!(instructions.contains("default next action is wait"));
464    }
465
466    #[test]
467    fn start_receipt_instructs_only_supported_controls() {
468        let receipt = AsyncOperationStartReceipt::new(
469            "media_generate_video_1",
470            AsyncOperationKind::Media,
471            AsyncControls::new(AsyncControl::Inspect).with(AsyncControl::Wait),
472        );
473        let value = serde_json::to_value(receipt).unwrap();
474
475        assert_eq!(value["operation_id"], "media_generate_video_1");
476        assert_eq!(value["kind"], "media");
477        assert_eq!(value["status"], "running");
478        assert_eq!(value["control_tools"].as_array().unwrap().len(), 2);
479        assert_eq!(value["control_tools"][0]["tool"], "inspect");
480        assert_eq!(
481            value["control_tools"][0]["suggested_arguments"]["operations"][0],
482            "media_generate_video_1"
483        );
484        assert_eq!(value["control_tools"][1]["tool"], "wait");
485        assert_eq!(
486            value["control_tools"][1]["suggested_arguments"]["kind"],
487            "media"
488        );
489    }
490
491    #[test]
492    fn async_operation_kind_uses_wire_names() {
493        assert_eq!(AsyncOperationKind::Ability.as_str(), "ability");
494        assert_eq!(AsyncOperationKind::Delegation.as_str(), "delegation");
495        assert_eq!(AsyncOperationKind::SubAgent.as_str(), "sub_agent");
496        assert_eq!(AsyncOperationKind::Shell.as_str(), "shell");
497        assert_eq!(AsyncOperationKind::Media.as_str(), "media");
498        assert_eq!(AsyncOperationKind::TaskExecution.as_str(), "task_execution");
499    }
500
501    #[test]
502    fn wait_args_deserialize_with_defaults() {
503        let args: WaitOperationsArgs = serde_json::from_value(json!({})).unwrap();
504
505        assert_eq!(args.seconds, 10);
506        assert_eq!(args.kind, None);
507    }
508
509    #[test]
510    fn wait_args_accept_whole_float_seconds_from_model_args() {
511        let args: WaitOperationsArgs = serde_json::from_value(json!({
512            "kind": "ability",
513            "seconds": 30.0
514        }))
515        .unwrap();
516
517        assert_eq!(args.seconds, 30);
518        assert_eq!(args.kind, Some(AsyncOperationKind::Ability));
519    }
520
521    #[test]
522    fn wait_args_accept_digit_string_seconds_from_model_args() {
523        let args: WaitOperationsArgs = serde_json::from_value(json!({
524            "kind": "ability",
525            "seconds": "10"
526        }))
527        .unwrap();
528
529        assert_eq!(args.seconds, 10);
530        assert_eq!(args.kind, Some(AsyncOperationKind::Ability));
531    }
532
533    #[test]
534    fn wait_args_reject_fractional_seconds() {
535        let err = serde_json::from_value::<WaitOperationsArgs>(json!({
536            "seconds": 5.5
537        }))
538        .unwrap_err();
539
540        assert!(err.to_string().contains("whole number"));
541    }
542
543    #[test]
544    fn numeric_coercion_accepts_u64_max_without_rounding() {
545        #[derive(Deserialize)]
546        struct Args {
547            #[serde(deserialize_with = "deserialize_u64_from_json_number")]
548            value: u64,
549        }
550
551        let integer: Args = serde_json::from_str(r#"{"value":18446744073709551615}"#).unwrap();
552        let string: Args = serde_json::from_value(json!({
553            "value": "18446744073709551615"
554        }))
555        .unwrap();
556
557        assert_eq!(integer.value, u64::MAX);
558        assert_eq!(string.value, u64::MAX);
559    }
560
561    #[test]
562    fn numeric_coercion_rejects_values_at_or_above_two_to_the_64th() {
563        #[derive(Debug, Deserialize)]
564        struct Args {
565            #[serde(deserialize_with = "deserialize_u64_from_json_number")]
566            #[allow(dead_code)]
567            value: u64,
568        }
569
570        let numeric =
571            serde_json::from_str::<Args>(r#"{"value":1.8446744073709552e19}"#).unwrap_err();
572        let string = serde_json::from_value::<Args>(json!({
573            "value": "18446744073709551616"
574        }))
575        .unwrap_err();
576
577        assert!(numeric.to_string().contains("whole number"));
578        assert!(string.to_string().contains("number too large"));
579    }
580
581    #[test]
582    fn inspect_args_accept_whole_float_limit_from_model_args() {
583        let args: InspectOperationsArgs = serde_json::from_value(json!({
584            "operations": ["ability_build_agent_2"],
585            "include_transcript": true,
586            "limit": 5.0
587        }))
588        .unwrap();
589
590        assert_eq!(args.limit, 5);
591    }
592
593    #[test]
594    fn inspect_args_accept_json_encoded_model_values() {
595        let args: InspectOperationsArgs = serde_json::from_value(json!({
596            "operations": "[\"ability_build_routine_1\"]",
597            "include_transcript": "true",
598            "limit": "5"
599        }))
600        .unwrap();
601
602        assert_eq!(args.operations, ["ability_build_routine_1"]);
603        assert!(args.include_transcript);
604        assert_eq!(args.limit, 5);
605    }
606
607    #[test]
608    fn operation_controls_share_json_encoded_operation_id_compatibility() {
609        let stop: StopOperationsArgs = serde_json::from_value(json!({
610            "operations": "[\"ability_build_routine_1\"]"
611        }))
612        .unwrap();
613        let send: SendOperationInputArgs = serde_json::from_value(json!({
614            "operations": "[\"ability_build_routine_1\"]",
615            "message": "continue"
616        }))
617        .unwrap();
618
619        assert_eq!(stop.operations, ["ability_build_routine_1"]);
620        assert_eq!(send.operations, ["ability_build_routine_1"]);
621    }
622
623    #[test]
624    fn inspect_args_reject_ambiguous_string_values() {
625        let operations_err = serde_json::from_value::<InspectOperationsArgs>(json!({
626            "operations": "ability_build_routine_1"
627        }))
628        .unwrap_err();
629        let bool_err = serde_json::from_value::<InspectOperationsArgs>(json!({
630            "include_transcript": "yes"
631        }))
632        .unwrap_err();
633
634        assert!(operations_err.to_string().contains("JSON-encoded array"));
635        assert!(bool_err.to_string().contains("expected a boolean"));
636    }
637
638    #[test]
639    fn inspect_args_reject_fractional_limit() {
640        let err = serde_json::from_value::<InspectOperationsArgs>(json!({
641            "limit": 5.5
642        }))
643        .unwrap_err();
644
645        assert!(err.to_string().contains("whole number"));
646    }
647
648    #[test]
649    fn wait_args_reject_non_digit_string_seconds() {
650        for seconds in ["5.5", "-1", "ten"] {
651            let err = serde_json::from_value::<WaitOperationsArgs>(json!({
652                "seconds": seconds
653            }))
654            .unwrap_err();
655
656            assert!(err.to_string().contains("whole number"));
657        }
658    }
659}