pawan-core 0.5.8

Pawan (पवन) — Core library: agent, tools, config, healing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Sub-agent spawning tool
//!
//! Spawns a pawan subprocess to handle a task independently.
//! This is the OMO replacement — enables multi-agent orchestration.

use super::Tool;
use crate::{PawanError, Result};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tracing;

use crate::subagent::SubagentHandle;

/// Tool for spawning a sub-agent (pawan subprocess)
pub struct SpawnAgentTool {
    workspace_root: PathBuf,
}

impl SpawnAgentTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }

    /// Find the pawan binary — tries cargo target first, then PATH
    fn find_pawan_binary(&self) -> String {
        // Check for debug/release binary in workspace target
        for candidate in &[
            self.workspace_root.join("target/release/pawan"),
            self.workspace_root.join("target/debug/pawan"),
        ] {
            if candidate.exists() {
                return candidate.to_string_lossy().to_string();
            }
        }
        // Fall back to PATH
        "pawan".to_string()
    }
}

#[async_trait]
impl Tool for SpawnAgentTool {
    fn name(&self) -> &str {
        "spawn_agent"
    }

    fn description(&self) -> &str {
        "Spawn a sub-agent (pawan subprocess) to handle a task independently. \
         Returns the agent's response as JSON. Use this for parallel or delegated tasks."
    }

    fn mutating(&self) -> bool {
        true // Spawning agents can mutate state
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": "The task/prompt for the sub-agent"
                },
                "model": {
                    "type": "string",
                    "description": "Model to use (optional, defaults to parent's model)"
                },
                "timeout": {
                    "type": "integer",
                    "description": "Timeout in seconds (default: 120)"
                },
                "workspace": {
                    "type": "string",
                    "description": "Workspace directory for the sub-agent (default: same as parent)"
                },
                "retries": {
                    "type": "integer",
                    "description": "Number of retry attempts on failure (default: 0, max: 2)"
                }
            },
            "required": ["prompt"]
        })
    }

    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        use thulp_core::{Parameter, ParameterType};
        thulp_core::ToolDefinition::builder("spawn_agent")
            .description(self.description())
            .parameter(
                Parameter::builder("prompt")
                    .param_type(ParameterType::String)
                    .required(true)
                    .description("The task/prompt for the sub-agent")
                    .build(),
            )
            .parameter(
                Parameter::builder("model")
                    .param_type(ParameterType::String)
                    .required(false)
                    .description("Model to use (optional, defaults to parent's model)")
                    .build(),
            )
            .parameter(
                Parameter::builder("timeout")
                    .param_type(ParameterType::Integer)
                    .required(false)
                    .description("Timeout in seconds (default: 120)")
                    .build(),
            )
            .parameter(
                Parameter::builder("workspace")
                    .param_type(ParameterType::String)
                    .required(false)
                    .description("Workspace directory for the sub-agent (default: same as parent)")
                    .build(),
            )
            .parameter(
                Parameter::builder("retries")
                    .param_type(ParameterType::Integer)
                    .required(false)
                    .description("Number of retry attempts on failure (default: 0, max: 2)")
                    .build(),
            )
            .build()
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        let prompt = args["prompt"]
            .as_str()
            .ok_or_else(|| PawanError::Tool("prompt is required for spawn_agent".into()))?;

        let timeout = args["timeout"].as_u64().unwrap_or(120);
        let model = args["model"].as_str();
        let workspace = args["workspace"]
            .as_str()
            .map(PathBuf::from)
            .unwrap_or_else(|| self.workspace_root.clone());
        let max_retries = args["retries"].as_u64().unwrap_or(0).min(2) as usize;

        // Generate unique agent ID for progress tracking
        let label: String = prompt
            .lines()
            .next()
            .unwrap_or(prompt)
            .chars()
            .take(48)
            .collect();
        let progress = SubagentHandle::start(&label, "spawn_agent", None);

        let agent_id = progress.id().to_string();
        let status_path = format!("/tmp/pawan-agent-{}.status", agent_id);
        let started_at = chrono::Utc::now().to_rfc3339();

        let pawan_bin = self.find_pawan_binary();

        for attempt in 0..=max_retries {
            let mut cmd = Command::new(&pawan_bin);
            cmd.arg("run")
                .arg("-o")
                .arg("json")
                .arg("--timeout")
                .arg(timeout.to_string())
                .arg("-w")
                .arg(workspace.to_string_lossy().to_string());

            if let Some(m) = model {
                cmd.arg("-m").arg(m);
            }

            cmd.arg(prompt);

            cmd.stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .stdin(Stdio::null());

            // Write initial status
            if let Ok(mut f) = std::fs::File::create(&status_path) {
                let _ = write!(
                    f,
                    r#"{{"state":"running","prompt":"{}","started_at":"{}","attempt":{}}}"#,
                    prompt
                        .chars()
                        .take(100)
                        .collect::<String>()
                        .replace('"', "'"),
                    started_at,
                    attempt + 1
                );
            }

            let mut child = match cmd.spawn() {
                Ok(c) => c,
                Err(e) => {
                    progress.complete_err(format!("spawn failed: {e}"));
                    progress.dismiss();
                    return Err(PawanError::Tool(format!(
                        "Failed to spawn sub-agent: {e}. Binary: {pawan_bin}"
                    )));
                }
            };

            let mut stdout = String::new();
            let mut stderr = String::new();

            if let Some(mut handle) = child.stdout.take() {
                handle.read_to_string(&mut stdout).await.ok();
            }
            if let Some(mut handle) = child.stderr.take() {
                handle.read_to_string(&mut stderr).await.ok();
            }

            let status = match child.wait().await {
                Ok(s) => s,
                Err(e) => {
                    progress.complete_err(format!("wait failed: {e}"));
                    progress.dismiss();
                    return Err(PawanError::Io(e));
                }
            };

            let result = if let Ok(json_result) = serde_json::from_str::<Value>(&stdout) {
                json_result
            } else {
                json!({
                    "content": stdout.trim(),
                    "raw_output": true
                })
            };

            if status.success() || attempt == max_retries {
                // Update status file with completion
                let duration_ms = chrono::Utc::now()
                    .signed_duration_since(
                        chrono::DateTime::parse_from_rfc3339(&started_at).unwrap_or_default(),
                    )
                    .num_milliseconds();
                if let Ok(mut f) = std::fs::File::create(&status_path) {
                    let state = if status.success() { "done" } else { "failed" };
                    let _ = write!(
                        f,
                        r#"{{"state":"{}","exit_code":{},"duration_ms":{},"attempt":{}}}"#,
                        state,
                        status.code().unwrap_or(-1),
                        duration_ms,
                        attempt + 1
                    );
                }

                if status.success() {
                    progress.complete_ok();
                } else {
                    progress.complete_err(format!(
                        "exit code {}",
                        status.code().unwrap_or(-1)
                    ));
                }
                let out = json!({
                    "success": status.success(),
                    "attempt": attempt + 1,
                    "total_attempts": attempt + 1,
                    "result": result,
                    "stderr": stderr.trim(),
                    "subagent_id": progress.id(),
                    "duration_ms": duration_ms,
                });
                progress.dismiss();
                return Ok(out);
            }
            // Failed but retries remaining — continue loop
            // Failed but retries remaining — continue loop
            tracing::warn!(
                attempt = attempt + 1,
                "spawn_agent attempt failed, retrying"
            );
        }

        progress.complete_err("all retry attempts exhausted");
        progress.dismiss();
        Err(PawanError::Tool(
            "spawn_agent: all retry attempts exhausted".into(),
        ))
    }
}

/// Tool for spawning multiple sub-agents in parallel
pub struct SpawnAgentsTool {
    workspace_root: PathBuf,
}

impl SpawnAgentsTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }
}

#[async_trait]
impl Tool for SpawnAgentsTool {
    fn name(&self) -> &str {
        "spawn_agents"
    }

    fn description(&self) -> &str {
        "Spawn multiple sub-agents in parallel. Each task runs concurrently and results are returned as an array."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "tasks": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "prompt": {"type": "string"},
                            "model": {"type": "string"},
                            "timeout": {"type": "integer"},
                            "workspace": {"type": "string"}
                        },
                        "required": ["prompt"]
                    }
                }
            },
            "required": ["tasks"]
        })
    }

    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        use thulp_core::{Parameter, ParameterType};
        thulp_core::ToolDefinition::builder("spawn_agents")
            .description(self.description())
            .parameter(Parameter::builder("tasks").param_type(ParameterType::Array).required(true)
                .description("Array of task objects, each with prompt (required), model, timeout, workspace").build())
            .build()
    }

    fn mutating(&self) -> bool {
        true // Spawning agents can mutate state
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        let tasks = args["tasks"]
            .as_array()
            .ok_or_else(|| PawanError::Tool("tasks array is required for spawn_agents".into()))?;

        for (index, task) in tasks.iter().enumerate() {
            if task.get("prompt").and_then(|p| p.as_str()).is_none() {
                return Err(PawanError::Tool(format!(
                    "spawn_agents: task {index} is missing prompt"
                )));
            }
        }

        let single_tool = SpawnAgentTool::new(self.workspace_root.clone());

        let futures: Vec<_> = tasks
            .iter()
            .enumerate()
            .map(|(index, task)| {
                let tool = &single_tool;
                let task = task.clone();
                async move {
                    let started = std::time::Instant::now();
                    let result = tool.execute(task).await;
                    (index, started.elapsed().as_millis() as u64, result)
                }
            })
            .collect();

        let results = futures::future::join_all(futures).await;

        let mut succeeded = 0usize;
        let mut failed = 0usize;
        let mut output: Vec<Value> = Vec::with_capacity(results.len());

        for (index, duration_ms, result) in results {
            match result {
                Ok(mut v) => {
                    if v.get("success").and_then(|s| s.as_bool()) == Some(true) {
                        succeeded += 1;
                    } else {
                        failed += 1;
                    }
                    if let Some(obj) = v.as_object_mut() {
                        obj.insert("index".into(), json!(index));
                        obj.insert("duration_ms".into(), json!(duration_ms));
                    }
                    output.push(v);
                }
                Err(e) => {
                    failed += 1;
                    output.push(json!({
                        "index": index,
                        "success": false,
                        "error": e.to_string(),
                        "duration_ms": duration_ms,
                    }));
                }
            }
        }

        let total = tasks.len();
        Ok(json!({
            "success": failed == 0,
            "total_tasks": total,
            "succeeded": succeeded,
            "failed": failed,
            "results": output,
        }))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    #[test]
    fn test_spawn_agent_tool_name() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        assert_eq!(tool.name(), "spawn_agent");
    }

    #[test]
    fn test_spawn_agents_tool_name() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        assert_eq!(tool.name(), "spawn_agents");
    }

    #[test]
    fn test_spawn_agent_schema_has_prompt() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let schema = tool.parameters_schema();
        assert!(schema["properties"]["prompt"].is_object());
        assert!(schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .any(|v| v == "prompt"));
    }

    #[test]
    fn test_find_pawan_binary_prefers_release_over_debug() {
        let tmp = TempDir::new().unwrap();
        // Create both release and debug pawan binaries
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        std::fs::create_dir_all(tmp.path().join("target/debug")).unwrap();
        let release = tmp.path().join("target/release/pawan");
        let debug = tmp.path().join("target/debug/pawan");
        std::fs::write(&release, "#!/bin/sh\necho release").unwrap();
        std::fs::write(&debug, "#!/bin/sh\necho debug").unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let binary = tool.find_pawan_binary();
        assert_eq!(
            binary,
            release.to_string_lossy().to_string(),
            "release binary must win over debug"
        );
    }

    #[test]
    fn test_find_pawan_binary_falls_back_to_debug_when_no_release() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/debug")).unwrap();
        let debug = tmp.path().join("target/debug/pawan");
        std::fs::write(&debug, "#!/bin/sh\necho debug").unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let binary = tool.find_pawan_binary();
        assert_eq!(binary, debug.to_string_lossy().to_string());
    }

    #[test]
    fn test_find_pawan_binary_falls_through_to_path_when_nothing_in_workspace() {
        let tmp = TempDir::new().unwrap();
        // No target/ at all
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let binary = tool.find_pawan_binary();
        // Falls back to bare "pawan" name (will be resolved via PATH at exec time)
        assert_eq!(binary, "pawan");
    }

    #[tokio::test]
    async fn test_spawn_agent_missing_prompt_errors() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        // No "prompt" field in args
        let result = tool.execute(json!({ "model": "test-model" })).await;
        assert!(result.is_err(), "missing prompt must error");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("prompt"),
            "error message should mention prompt, got: {}",
            err
        );
    }

    #[test]
    fn test_spawn_agents_schema_requires_tasks_array() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let schema = tool.parameters_schema();
        let required = schema["required"].as_array().unwrap();
        assert!(
            required.iter().any(|v| v == "tasks"),
            "tasks must be required"
        );
        // tasks should be declared as an array type with an items.required = [prompt]
        let tasks_type = schema["properties"]["tasks"]["type"].as_str();
        assert_eq!(tasks_type, Some("array"));
    }

    #[tokio::test]
    async fn test_spawn_agents_empty_tasks_succeeds_with_zero_results() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let result = tool.execute(json!({ "tasks": [] })).await.unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["total_tasks"], 0);
        assert_eq!(result["results"].as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_spawn_agents_missing_tasks_errors() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        // tasks field absent entirely
        let result = tool.execute(json!({})).await;
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("tasks"));
    }

    #[tokio::test]
    async fn test_spawn_agent_prompt_non_string_errors() {
        // Prompt present but as integer — `.as_str()` returns None so
        // ok_or_else must fire. Guards against a refactor that silently
        // coerces numeric prompts (which would then panic or send garbage
        // to the pawan run subcommand).
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool.execute(json!({ "prompt": 42 })).await;
        assert!(result.is_err(), "non-string prompt must error");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("prompt"),
            "error should mention 'prompt', got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_spawn_agents_tasks_non_array_errors() {
        // tasks present but as string — `.as_array()` returns None so
        // ok_or_else must fire. Prevents silent coercion.
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let result = tool.execute(json!({ "tasks": "not an array" })).await;
        assert!(result.is_err(), "non-array tasks must error");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("tasks"),
            "error should mention 'tasks', got: {}",
            err
        );
    }

    #[test]
    fn test_spawn_agent_schema_lists_all_optional_params() {
        // All 5 advertised parameters must be declared as schema properties.
        // If someone adds a new one without updating the schema, consumers
        // that introspect parameters_schema() will miss it.
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let schema = tool.parameters_schema();
        let props = schema["properties"].as_object().unwrap();
        for p in &["prompt", "model", "timeout", "workspace", "retries"] {
            assert!(props.contains_key(*p), "schema missing '{}'", p);
        }
        // Only prompt is required
        let required = schema["required"].as_array().unwrap();
        assert_eq!(required.len(), 1);
        assert_eq!(required[0], "prompt");
    }

    #[test]
    fn test_spawn_agents_schema_tasks_items_has_prompt_required() {
        // The nested items schema inside tasks must mark prompt required —
        // otherwise the array can hold task objects missing the prompt
        // field, and each sub-execute() would error one-by-one instead of
        // validating up front.
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let schema = tool.parameters_schema();
        let items_required = schema["properties"]["tasks"]["items"]["required"]
            .as_array()
            .expect("tasks.items.required should exist");
        assert!(items_required.iter().any(|v| v == "prompt"));
    }

    #[test]
    fn test_spawn_agent_thulp_definition_has_all_5_params() {
        // thulp_definition() must mirror parameters_schema() — if they drift,
        // thulp-registry callers will see a different API than MCP callers.
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let def = tool.thulp_definition();
        assert_eq!(def.name, "spawn_agent");
        let param_names: Vec<&str> = def.parameters.iter().map(|p| p.name.as_str()).collect();
        for p in &["prompt", "model", "timeout", "workspace", "retries"] {
            assert!(param_names.contains(p), "thulp definition missing '{}'", p);
        }
        // Only prompt is required
        let required_count = def.parameters.iter().filter(|p| p.required).count();
        assert_eq!(required_count, 1, "only prompt should be required");
    }

    #[test]
    fn test_spawn_agents_thulp_definition_has_tasks_param() {
        // spawn_agents' thulp definition should declare exactly one required
        // parameter: tasks (an array). If this drifts, parallel-agent callers
        // get confused schemas.
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let def = tool.thulp_definition();
        assert_eq!(def.name, "spawn_agents");
        assert_eq!(def.parameters.len(), 1);
        let tasks_param = &def.parameters[0];
        assert_eq!(tasks_param.name, "tasks");
        assert!(tasks_param.required);
    }

    #[test]
    fn test_spawn_agent_mutating_returns_true() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        assert!(tool.mutating(), "spawn_agent can mutate state");
    }

    #[test]
    fn test_spawn_agents_mutating_returns_true() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        assert!(tool.mutating(), "spawn_agents can mutate state");
    }

    #[test]
    fn test_spawn_agent_description_non_empty() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let desc = tool.description();
        assert!(!desc.is_empty());
        assert!(desc.contains("sub-agent"));
    }

    #[test]
    fn test_spawn_agents_description_non_empty() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let desc = tool.description();
        assert!(!desc.is_empty());
        assert!(desc.contains("parallel"));
    }

    #[tokio::test]
    async fn test_spawn_agent_timeout_defaults_to_120() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(
            &binary,
            r"#!/bin/sh
exit 0",
        )
        .unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool.execute(json!({"prompt": "test"})).await.unwrap();
        assert_eq!(result["success"], true);
    }

    #[tokio::test]
    async fn test_spawn_agent_custom_timeout() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(
            &binary,
            r"#!/bin/sh
exit 0",
        )
        .unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({"prompt": "test", "timeout": 60}))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
    }

    #[tokio::test]
    async fn test_spawn_agent_custom_model() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(&binary, "#!/bin/sh\necho '{\"content\":\"test response\"}'").unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({"prompt": "test", "model": "gpt-4"}))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["result"]["content"], "test response");
    }

    #[tokio::test]
    async fn test_spawn_agent_retries_on_failure() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        let counter_file = tmp.path().join("counter");
        std::fs::write(&counter_file, "0").unwrap();
        let script = format!(
            "#!/bin/sh\ncount=$(cat {})\necho $((count + 1)) > {}\nif [ $count -eq 0 ]; then\n    exit 1\nelse\n    exit 0\nfi",
            counter_file.display(), counter_file.display()
        );
        std::fs::write(&binary, script).unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({
                "prompt": "test",
                "retries": 1
            }))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["attempt"], 2);
        assert_eq!(result["total_attempts"], 2);
    }

    #[tokio::test]
    async fn test_spawn_agent_stderr_captured() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(
            &binary,
            r"#!/bin/sh
echo 'error message' >&2
exit 0",
        )
        .unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentTool::new(tmp.path().to_path_buf());
        let result = tool.execute(json!({"prompt": "test"})).await.unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["stderr"], "error message");
    }

    #[serial_test::serial(pawan_session_tests)]
    #[tokio::test]
    async fn test_spawn_agents_single_task() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(&binary, "#!/bin/sh\necho '{\"result\":\"done\"}'").unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({
                "tasks": [
                    {"prompt": "task1"}
                ]
            }))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["total_tasks"], 1);
        assert_eq!(result["results"].as_array().unwrap().len(), 1);
        assert_eq!(result["results"][0]["result"]["result"], "done");
    }

    #[serial_test::serial(pawan_session_tests)]
    #[tokio::test]
    async fn test_spawn_agents_multiple_tasks() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("target/release")).unwrap();
        let binary = tmp.path().join("target/release/pawan");
        std::fs::write(&binary, "#!/bin/sh\necho '{\"result\":\"done\"}'").unwrap();
        #[cfg(unix)]
        std::fs::set_permissions(&binary, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();

        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({
                "tasks": [
                    {"prompt": "task1"},
                    {"prompt": "task2"},
                    {"prompt": "task3"}
                ]
            }))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
        assert_eq!(result["total_tasks"], 3);
        assert_eq!(result["results"].as_array().unwrap().len(), 3);
    }

    #[tokio::test]
    async fn test_spawn_agents_task_missing_prompt() {
        let tmp = TempDir::new().unwrap();
        let tool = SpawnAgentsTool::new(tmp.path().to_path_buf());
        let result = tool
            .execute(json!({
                "tasks": [{"model": "gpt-4"}]
            }))
            .await;
        // Upfront validation now rejects tasks missing a prompt
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("missing prompt"));
    }
}