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