1use 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#[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#[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#[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.",
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.",
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.",
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 NeedsInput,
201 Completed,
202 Failed,
203 Stopped,
204}
205
206impl AsyncOperationSignalKind {
207 pub fn as_str(self) -> &'static str {
208 match self {
209 Self::Started => "started",
210 Self::Progress => "progress",
211 Self::NeedsInput => "needs_input",
212 Self::Completed => "completed",
213 Self::Failed => "failed",
214 Self::Stopped => "stopped",
215 }
216 }
217}
218
219#[derive(Debug, Clone, Deserialize)]
220pub struct InspectOperationsArgs {
221 #[serde(default)]
222 pub operations: Vec<String>,
223 #[serde(default)]
224 pub kind: Option<AsyncOperationKind>,
225 #[serde(default)]
226 pub include_transcript: bool,
227 #[serde(
228 default = "default_inspect_limit",
229 deserialize_with = "deserialize_usize_from_json_number"
230 )]
231 pub limit: usize,
232}
233
234#[derive(Debug, Clone, Deserialize)]
235pub struct StopOperationsArgs {
236 #[serde(default)]
237 pub operations: Vec<String>,
238 #[serde(default)]
239 pub kind: Option<AsyncOperationKind>,
240 pub reason: Option<String>,
241}
242
243#[derive(Debug, Clone, Deserialize)]
244pub struct WaitOperationsArgs {
245 #[serde(
246 default = "default_wait_seconds",
247 deserialize_with = "deserialize_u64_from_json_number"
248 )]
249 pub seconds: u64,
250 #[serde(default)]
251 pub kind: Option<AsyncOperationKind>,
252 pub reason: Option<String>,
253}
254
255#[derive(Debug, Clone, Deserialize)]
256pub struct SendOperationInputArgs {
257 #[serde(default)]
258 pub operations: Vec<String>,
259 pub message: String,
260}
261
262pub fn inspect_operations_parameters_schema() -> serde_json::Value {
263 json!({
264 "type": "object",
265 "properties": {
266 "operations": {"type": "array", "items": {"type": "string"}},
267 "kind": operation_kind_schema(),
268 "include_transcript": {"type": "boolean"},
269 "limit": {"type": "integer", "minimum": 1, "maximum": 50}
270 },
271 "additionalProperties": false
272 })
273}
274
275pub fn stop_operations_parameters_schema() -> serde_json::Value {
276 json!({
277 "type": "object",
278 "properties": {
279 "operations": {"type": "array", "items": {"type": "string"}},
280 "kind": operation_kind_schema(),
281 "reason": {"type": "string"}
282 },
283 "additionalProperties": false
284 })
285}
286
287pub fn wait_operations_parameters_schema() -> serde_json::Value {
288 json!({
289 "type": "object",
290 "properties": {
291 "seconds": {"type": "integer", "minimum": 1, "maximum": 30},
292 "kind": operation_kind_schema(),
293 "reason": {"type": "string"}
294 },
295 "additionalProperties": false
296 })
297}
298
299pub fn send_operation_input_parameters_schema() -> serde_json::Value {
300 json!({
301 "type": "object",
302 "properties": {
303 "operations": {"type": "array", "items": {"type": "string"}},
304 "message": {"type": "string"}
305 },
306 "required": ["operations", "message"],
307 "additionalProperties": false
308 })
309}
310
311pub fn operation_kind_schema() -> serde_json::Value {
312 json!({
313 "type": "string",
314 "enum": ["ability", "delegation", "sub_agent", "shell", "media", "task_execution"]
315 })
316}
317
318fn default_inspect_limit() -> usize {
319 30
320}
321
322pub fn deserialize_usize_from_json_number<'de, D>(deserializer: D) -> Result<usize, D::Error>
323where
324 D: Deserializer<'de>,
325{
326 let value = serde_json::Value::deserialize(deserializer)?;
327 match value {
328 serde_json::Value::Number(number) => {
329 if let Some(raw) = number.as_u64() {
330 usize::try_from(raw).map_err(serde::de::Error::custom)
331 } else if let Some(raw) = number.as_f64() {
332 if raw.is_finite() && raw.fract() == 0.0 && raw >= 0.0 {
333 usize::try_from(raw as u64).map_err(serde::de::Error::custom)
334 } else {
335 Err(serde::de::Error::custom(
336 "expected a non-negative whole number",
337 ))
338 }
339 } else {
340 Err(serde::de::Error::custom(
341 "expected a non-negative whole number",
342 ))
343 }
344 }
345 other => Err(serde::de::Error::custom(format!(
346 "expected a non-negative whole number, got {other}"
347 ))),
348 }
349}
350
351pub fn deserialize_u64_from_json_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
352where
353 D: Deserializer<'de>,
354{
355 let value = serde_json::Value::deserialize(deserializer)?;
356 match value {
357 serde_json::Value::Number(number) => {
358 if let Some(raw) = number.as_u64() {
359 Ok(raw)
360 } else if let Some(raw) = number.as_f64() {
361 if raw.is_finite() && raw.fract() == 0.0 && raw >= 0.0 {
362 Ok(raw as u64)
363 } else {
364 Err(serde::de::Error::custom(
365 "expected a non-negative whole number",
366 ))
367 }
368 } else {
369 Err(serde::de::Error::custom(
370 "expected a non-negative whole number",
371 ))
372 }
373 }
374 other => Err(serde::de::Error::custom(format!(
375 "expected a non-negative whole number, got {other}"
376 ))),
377 }
378}
379
380fn default_wait_seconds() -> u64 {
381 10
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 #[test]
389 fn async_controls_track_explicit_capabilities() {
390 let controls = AsyncControls::new(AsyncControl::Inspect).with(AsyncControl::Wait);
391
392 assert!(controls.contains(AsyncControl::Inspect));
393 assert!(controls.contains(AsyncControl::Wait));
394 assert!(!controls.contains(AsyncControl::SendInput));
395 assert!(!controls.contains(AsyncControl::Stop));
396 }
397
398 #[test]
399 fn start_receipt_instructs_only_supported_controls() {
400 let receipt = AsyncOperationStartReceipt::new(
401 "media_generate_video_1",
402 AsyncOperationKind::Media,
403 AsyncControls::new(AsyncControl::Inspect).with(AsyncControl::Wait),
404 );
405 let value = serde_json::to_value(receipt).unwrap();
406
407 assert_eq!(value["operation_id"], "media_generate_video_1");
408 assert_eq!(value["kind"], "media");
409 assert_eq!(value["status"], "running");
410 assert_eq!(value["control_tools"].as_array().unwrap().len(), 2);
411 assert_eq!(value["control_tools"][0]["tool"], "inspect");
412 assert_eq!(
413 value["control_tools"][0]["suggested_arguments"]["operations"][0],
414 "media_generate_video_1"
415 );
416 assert_eq!(value["control_tools"][1]["tool"], "wait");
417 assert_eq!(
418 value["control_tools"][1]["suggested_arguments"]["kind"],
419 "media"
420 );
421 }
422
423 #[test]
424 fn async_operation_kind_uses_wire_names() {
425 assert_eq!(AsyncOperationKind::Ability.as_str(), "ability");
426 assert_eq!(AsyncOperationKind::Delegation.as_str(), "delegation");
427 assert_eq!(AsyncOperationKind::SubAgent.as_str(), "sub_agent");
428 assert_eq!(AsyncOperationKind::Shell.as_str(), "shell");
429 assert_eq!(AsyncOperationKind::Media.as_str(), "media");
430 assert_eq!(AsyncOperationKind::TaskExecution.as_str(), "task_execution");
431 }
432
433 #[test]
434 fn wait_args_deserialize_with_defaults() {
435 let args: WaitOperationsArgs = serde_json::from_value(json!({})).unwrap();
436
437 assert_eq!(args.seconds, 10);
438 assert_eq!(args.kind, None);
439 }
440
441 #[test]
442 fn wait_args_accept_whole_float_seconds_from_model_args() {
443 let args: WaitOperationsArgs = serde_json::from_value(json!({
444 "kind": "ability",
445 "seconds": 30.0
446 }))
447 .unwrap();
448
449 assert_eq!(args.seconds, 30);
450 assert_eq!(args.kind, Some(AsyncOperationKind::Ability));
451 }
452
453 #[test]
454 fn wait_args_reject_fractional_seconds() {
455 let err = serde_json::from_value::<WaitOperationsArgs>(json!({
456 "seconds": 5.5
457 }))
458 .unwrap_err();
459
460 assert!(err.to_string().contains("whole number"));
461 }
462
463 #[test]
464 fn inspect_args_accept_whole_float_limit_from_model_args() {
465 let args: InspectOperationsArgs = serde_json::from_value(json!({
466 "operations": ["ability_build_agent_2"],
467 "include_transcript": true,
468 "limit": 5.0
469 }))
470 .unwrap();
471
472 assert_eq!(args.limit, 5);
473 }
474
475 #[test]
476 fn inspect_args_reject_fractional_limit() {
477 let err = serde_json::from_value::<InspectOperationsArgs>(json!({
478 "limit": 5.5
479 }))
480 .unwrap_err();
481
482 assert!(err.to_string().contains("whole number"));
483 }
484}