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