everruns-core 0.17.5

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
// Subagent Capability
//
// Decision: 1 creation tool — spawn_subagent.
// - spawn_subagent creates a child session with parent_session_id set
//
// Blueprint support: spawn_subagent accepts optional `blueprint` and `config`
// params. When blueprint is set, the child session uses the blueprint's
// RuntimeAgent (own prompt, tools, model) instead of inheriting parent's.
//
// Background mode (default): returns immediately with a task_id; a detached
// watcher (same pattern as spawn_background runs) sends the instructions,
// heartbeats the task registry, and settles the task on the child's terminal
// turn status. The task's OnTerminal wake policy notifies the parent session
// through the registry-level waker (specs/session-tasks.md, Wake-ups).
// Foreground mode: blocks until subagent completes (send_message + wait_for_idle).
// When no session task registry is wired (embedders without background
// tracking), an unspecified mode degrades to foreground so results are not lost.
//
// Subagent naming: human-readable ("Test Runner"), unique per parent, case-insensitive.
// Nesting prevention: rejects spawn if current session has parent_session_id set.

use super::{Capability, CapabilityLocalization, CapabilityStatus};
use crate::platform_store::PlatformStore;
use crate::session_task::{
    CreateSessionTask, SessionTask, SessionTaskFilter, SessionTaskState, SessionTaskUpdate,
    TASK_KIND_SUBAGENT, TaskError, TaskExecutor, TaskExecutorPlugin, TaskLinks, TaskMessage,
    TaskWakePolicy, task_message_text,
};
use crate::tool_types::ToolHints;
use crate::tools::{Tool, ToolExecutionResult};
use crate::traits::{SpawnClaimResult, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

pub const SUBAGENTS_CAPABILITY_ID: &str = "subagents";

/// Subagent capability — spawn and manage child agent sessions.
pub struct SubagentCapability;

impl Capability for SubagentCapability {
    fn id(&self) -> &str {
        SUBAGENTS_CAPABILITY_ID
    }

    fn name(&self) -> &str {
        "Subagents"
    }

    fn description(&self) -> &str {
        "Spawn and manage subagents for parallel task execution in isolated context windows."
    }

    fn localizations(&self) -> Vec<CapabilityLocalization> {
        vec![CapabilityLocalization::text(
            "uk",
            "Субагенти",
            "Запускайте субагентів і керуйте ними для паралельного виконання завдань в ізольованих контекстних вікнах.",
        )]
    }

    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    fn icon(&self) -> Option<&str> {
        Some("git-branch")
    }

    fn category(&self) -> Option<&str> {
        Some("Core")
    }

    fn features(&self) -> Vec<&'static str> {
        vec!["subagents"]
    }

    fn system_prompt_addition(&self) -> Option<&str> {
        Some(SUBAGENT_SYSTEM_PROMPT)
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![Box::new(SpawnSubagentTool)]
    }
}

const SUBAGENT_SYSTEM_PROMPT: &str = "Spawn subagents only for independent workstreams that benefit from parallelism or a separate context window; do not delegate immediate sequential steps. Spawns are background by default: you get a task_id, keep working, and are notified on completion (monitor with get_task/wait_task). Use mode \"foreground\" only when you cannot proceed without the result. No nested subagents. Use blueprints for specialist agents with their own tools and model.";

/// Execution mode for spawn_subagent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpawnMode {
    /// Return immediately; a detached watcher settles the task and the
    /// OnTerminal wake policy notifies the parent when the child finishes.
    Background,
    /// Block until the child idles and return its result inline.
    Foreground,
}

impl SpawnMode {
    fn as_str(self) -> &'static str {
        match self {
            Self::Background => "background",
            Self::Foreground => "foreground",
        }
    }
}

/// Per-slice wait used by the background watcher; the watcher loops slices
/// until the child reaches a terminal state or the overall cap is hit.
const BACKGROUND_WAIT_SLICE_SECS: u64 = 300;
/// Overall cap on a background subagent run. The child's own max-iterations
/// guard bounds each turn; this bounds pathological never-terminal children.
const BACKGROUND_MAX_WAIT_SECS: u64 = 6 * 60 * 60;
/// Watcher heartbeat cadence; the session task reaper treats heartbeats
/// stale after ~5 minutes, so this keeps live watchers well inside that.
const BACKGROUND_HEARTBEAT_INTERVAL_SECS: u64 = 15;
/// Backoff between wait slices for statuses that return immediately
/// (paused / waiting_for_tool_results) so the watcher does not spin.
const BACKGROUND_POLL_BACKOFF_SECS: u64 = 5;

fn terminal_subagent_status(wait_status: &str) -> Option<crate::session::SubagentStatus> {
    match wait_status {
        // Plain `idle` only means the worker is ready for another turn — failed
        // turns also leave the session idle — so only explicit terminal
        // outcomes may settle the spawn handle and persist terminal metadata.
        "completed" => Some(crate::session::SubagentStatus::Completed),
        "error" | "failed" => Some(crate::session::SubagentStatus::Failed),
        "cancelled" => Some(crate::session::SubagentStatus::Cancelled),
        "max_iterations_reached" => Some(crate::session::SubagentStatus::MaxIterationsReached),
        // A sealed turn (no forward progress / budget exhausted) is terminal but
        // distinct from a failure — surface it so the parent can decide next steps.
        "sealed" => Some(crate::session::SubagentStatus::Sealed),
        _ => None,
    }
}

fn terminal_subagent_task_state(
    subagent_status: &crate::session::SubagentStatus,
) -> SessionTaskState {
    match subagent_status {
        crate::session::SubagentStatus::Completed => SessionTaskState::Succeeded,
        crate::session::SubagentStatus::Cancelled => SessionTaskState::Canceled,
        _ => SessionTaskState::Failed,
    }
}

// =============================================================================
// Helper: get platform store from context
// =============================================================================

use super::util::{get_platform_store, require_str_nonblank as require_str};

fn get_session_store(
    context: &ToolContext,
) -> Result<&dyn crate::traits::SessionStore, ToolExecutionResult> {
    context
        .session_store
        .as_ref()
        .map(|s| s.as_ref())
        .ok_or_else(|| {
            ToolExecutionResult::tool_error("Subagent tools require session_store context")
        })
}

/// Extract the last assistant/agent message content from a list of messages.
fn last_agent_message(messages: &[crate::platform_store::PlatformMessage]) -> Option<String> {
    messages
        .iter()
        .rfind(|m| m.role == "agent" || m.role == "assistant")
        .map(|m| m.content.clone())
}

/// Truncated human summary stored on the subagent's task record.
const MAX_TASK_SUMMARY_CHARS: usize = 2_048;

fn truncate_summary(text: &str) -> String {
    let mut chars = text.chars();
    let truncated: String = chars.by_ref().take(MAX_TASK_SUMMARY_CHARS).collect();
    if chars.next().is_some() {
        format!("{truncated}\n[truncated]")
    } else {
        truncated
    }
}

/// Mirror a terminal outcome onto the subagent's session task (best-effort;
/// tolerates a missing registry or task).
async fn finish_subagent_task(
    context: &ToolContext,
    task_id: Option<&str>,
    state: SessionTaskState,
    summary: Option<String>,
    error: Option<TaskError>,
) {
    let (Some(registry), Some(task_id)) = (context.session_task_registry.as_ref(), task_id) else {
        return;
    };
    let _ = registry
        .update(
            context.session_id,
            task_id,
            SessionTaskUpdate {
                state: Some(state),
                summary,
                error,
                ..Default::default()
            },
        )
        .await;
}

/// Find the session task tracking a subagent by its child session id.
async fn find_subagent_task(
    context: &ToolContext,
    child_id: crate::typed_id::SessionId,
) -> Option<SessionTask> {
    let registry = context.session_task_registry.as_ref()?;
    let tasks = registry
        .list(
            context.session_id,
            Some(&SessionTaskFilter {
                kind: Some(TASK_KIND_SUBAGENT.to_string()),
                state: None,
            }),
        )
        .await
        .ok()?;
    tasks
        .into_iter()
        .find(|task| task.links.child_session_id == Some(child_id))
}

// =============================================================================
// Tool: spawn_subagent
// =============================================================================

pub struct SpawnSubagentTool;

#[async_trait]
impl Tool for SpawnSubagentTool {
    fn narrate(
        &self,
        tool_call: &crate::tool_types::ToolCall,
        phase: crate::tool_narration::ToolNarrationPhase,
        locale: Option<&str>,
    ) -> Option<String> {
        Some(crate::tool_narration::narrate_spawn_subagent(
            &tool_call.arguments,
            phase,
            locale,
        ))
    }

    fn name(&self) -> &str {
        "spawn_subagent"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Spawn Subagent")
    }

    fn description(&self) -> &str {
        "Spawn a named subagent to handle a specific task in its own context window. Runs in the background by default and returns a task_id immediately; set mode to \"foreground\" to block until it completes. Use `blueprint` to spawn a specialist agent with its own tools and model."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Human-readable name for the subagent (e.g. 'Test Runner', 'Auth Explorer'). Must be unique within this session."
                },
                "instructions": {
                    "type": "string",
                    "description": "Instructions for the subagent — what it should do."
                },
                "mode": {
                    "type": "string",
                    "enum": ["background", "foreground"],
                    "description": "Execution mode. \"background\" (default) returns immediately with a task_id — monitor with get_task/wait_task; the session is notified when the subagent finishes. \"foreground\" blocks until the subagent completes and returns its result inline."
                },
                "blueprint": {
                    "type": "string",
                    "description": "Blueprint ID to spawn a specialist agent with its own tools and model. Omit to inherit parent's configuration."
                },
                "config": {
                    "type": "object",
                    "description": "Blueprint-specific configuration. Only valid when `blueprint` is set. Validated against the blueprint's config schema."
                }
            },
            "required": ["name", "instructions"],
            "additionalProperties": false
        })
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default().with_long_running(true)
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "spawn_subagent requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        spawn_subagent_impl(arguments, context)
            .await
            .unwrap_or_else(|e| e)
    }

    fn requires_context(&self) -> bool {
        true
    }
}

/// Resolve the effective spawn mode from the `mode` argument.
///
/// Background needs a session task registry (it is the only surface through
/// which the parent can observe the result): an explicit `background` without
/// one is an error, while the unspecified default degrades to foreground so
/// embedders without background tracking keep blocking semantics.
fn resolve_spawn_mode(
    arguments: &Value,
    context: &ToolContext,
) -> Result<SpawnMode, ToolExecutionResult> {
    let explicit = match arguments
        .get("mode")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        None => None,
        Some("background") => Some(SpawnMode::Background),
        Some("foreground") => Some(SpawnMode::Foreground),
        Some(other) => {
            return Err(ToolExecutionResult::tool_error(format!(
                "Invalid mode: \"{other}\". Valid modes: background, foreground."
            )));
        }
    };
    let has_registry = context.session_task_registry.is_some();
    match explicit {
        Some(SpawnMode::Background) if !has_registry => Err(ToolExecutionResult::tool_error(
            "Background mode requires a session task registry, which is not available in this environment. Use mode: \"foreground\" instead.",
        )),
        Some(mode) => Ok(mode),
        None if has_registry => Ok(SpawnMode::Background),
        None => Ok(SpawnMode::Foreground),
    }
}

async fn spawn_subagent_impl(
    arguments: Value,
    context: &ToolContext,
) -> Result<ToolExecutionResult, ToolExecutionResult> {
    let name = require_str(&arguments, "name")?.trim().to_string();
    let instructions = require_str(&arguments, "instructions")?.to_string();
    let mode = resolve_spawn_mode(&arguments, context)?;

    let store = get_platform_store(context)?;
    let session_store = get_session_store(context)?;

    let blueprint_param = arguments
        .get("blueprint")
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .map(|s| s.to_string());
    let config_param = arguments.get("config").filter(|v| !v.is_null()).cloned();

    // Reject config without blueprint
    if config_param.is_some() && blueprint_param.is_none() {
        return Ok(ToolExecutionResult::tool_error(
            "The `config` parameter is only valid when `blueprint` is set.",
        ));
    }

    // Nesting check: reject if current session is already a subagent
    let parent_session = match session_store.get_session(context.session_id).await {
        Ok(Some(s)) => s,
        Ok(None) => return Ok(ToolExecutionResult::tool_error("Current session not found")),
        Err(e) => return Err(ToolExecutionResult::internal_error(e)),
    };

    if parent_session.parent_session_id.is_some() {
        return Ok(ToolExecutionResult::tool_error(
            "Subagents cannot spawn other subagents (nesting not allowed).",
        ));
    }

    // Validate blueprint exists and is allowed for this parent session.
    if let Some(ref bp_id) = blueprint_param {
        let Some(ref registry) = context.capability_registry else {
            return Ok(ToolExecutionResult::tool_error(
                "Blueprint support requires capability_registry context.",
            ));
        };

        let Some((blueprint_capability_id, blueprint)) = registry.blueprint_with_capability(bp_id)
        else {
            return Ok(ToolExecutionResult::tool_error(format!(
                "Unknown blueprint: \"{bp_id}\". Check available blueprints."
            )));
        };

        // Validate config against schema if blueprint has one.
        if let Some(ref schema) = blueprint.config_schema
            && config_param.is_none()
            && schema
                .get("required")
                .is_some_and(|r| r.as_array().is_some_and(|arr| !arr.is_empty()))
        {
            return Ok(ToolExecutionResult::tool_error(format!(
                "Blueprint \"{bp_id}\" requires config. Schema: {}",
                serde_json::to_string_pretty(schema).unwrap_or_default()
            )));
        }

        let allowed_capability_ids = if let Some(agent_id) = parent_session.agent_id {
            match store.get_agent_by_id(agent_id).await {
                Ok(Some(agent)) => agent
                    .capabilities
                    .iter()
                    .map(|c| c.capability_id().to_string())
                    .collect::<Vec<_>>(),
                Ok(None) => vec![],
                Err(e) => return Err(ToolExecutionResult::internal_error(e)),
            }
        } else {
            match store.get_harness(parent_session.harness_id).await {
                Ok(Some(harness)) => harness
                    .capabilities
                    .iter()
                    .map(|c| c.capability_id().to_string())
                    .collect::<Vec<_>>(),
                Ok(None) => vec![],
                Err(e) => return Err(ToolExecutionResult::internal_error(e)),
            }
        };

        if !allowed_capability_ids
            .iter()
            .any(|capability_id| capability_id == &blueprint_capability_id)
        {
            return Ok(ToolExecutionResult::tool_error(format!(
                "Blueprint \"{bp_id}\" is not enabled for this session."
            )));
        }
    }

    // --- Durable spawn handle claim (EVE-535) ---
    //
    // When a spawn store and tool_call_id are available, attempt to claim a
    // spawn slot before creating the child session.  On reclaim, this lets us
    // reattach to the existing child instead of spawning a duplicate.
    if let (Some(spawn_store), Some(tool_call_id)) =
        (&context.subagent_spawn_store, &context.tool_call_id)
    {
        let claim_token = uuid::Uuid::new_v4();

        let claim = match spawn_store
            .try_claim_spawn(context.session_id, tool_call_id, claim_token)
            .await
        {
            Ok(c) => c,
            Err(e) => return Err(ToolExecutionResult::internal_error(e)),
        };

        match claim {
            SpawnClaimResult::AlreadySettled {
                child_session_id,
                terminal_status,
                terminal_result,
            } => {
                // Already settled on a previous execution: return stored result.
                let task_id = find_subagent_task(context, child_session_id)
                    .await
                    .map(|t| t.id);
                return Ok(ToolExecutionResult::success(json!({
                    "subagent_id": child_session_id.to_string(),
                    "name": name,
                    "status": terminal_status,
                    "result": terminal_result,
                    "task_id": task_id,
                    "blueprint": blueprint_param,
                })));
            }
            SpawnClaimResult::AlreadyRunning {
                child_session_id,
                claim_token: stored_claim_token,
            } => {
                // Child was spawned before but hasn't settled yet — reattach.
                // Use the stored claim_token so settle succeeds on this replay.
                let task = find_subagent_task(context, child_session_id).await;
                let (task_id, task_attempt) =
                    task.map(|t| (Some(t.id), t.attempt)).unwrap_or((None, 1));
                match mode {
                    SpawnMode::Foreground => {
                        return Ok(run_subagent_wait_and_settle(
                            store,
                            context,
                            child_session_id,
                            &name,
                            &instructions,
                            &blueprint_param,
                            task_id,
                            Some((
                                spawn_store.as_ref(),
                                tool_call_id.as_str(),
                                stored_claim_token,
                            )),
                        )
                        .await);
                    }
                    SpawnMode::Background => {
                        // Re-arm the detached watcher so the task still settles;
                        // the instructions were already sent on the first claim.
                        spawn_background_watcher(
                            context,
                            child_session_id,
                            &name,
                            None,
                            task_id.clone(),
                            task_attempt,
                            Some(stored_claim_token),
                        );
                        return Ok(background_running_result(
                            child_session_id,
                            &name,
                            &task_id,
                            &blueprint_param,
                        ));
                    }
                }
            }
            SpawnClaimResult::Claimed {
                spawn_handle_id,
                claim_token: actual_claim_token,
            }
            | SpawnClaimResult::ClaimedPendingChild {
                spawn_handle_id,
                claim_token: actual_claim_token,
            } => {
                // First claim (or re-claim after crash before register):
                // create child and register it durably before waiting.
                return Ok(spawn_create_and_wait(
                    store,
                    context,
                    &parent_session,
                    &name,
                    &instructions,
                    &blueprint_param,
                    &config_param,
                    mode,
                    Some((
                        spawn_store.as_ref(),
                        tool_call_id.as_str(),
                        spawn_handle_id,
                        actual_claim_token,
                    )),
                )
                .await);
            }
        }
    }

    // --- No-spawn-store path (dev / noop) ---
    Ok(spawn_create_and_wait(
        store,
        context,
        &parent_session,
        &name,
        &instructions,
        &blueprint_param,
        &config_param,
        mode,
        None,
    )
    .await)
}

/// Immediate tool result for a background spawn: the child is running and the
/// task record is the surface for progress and the final result.
fn background_running_result(
    child_id: crate::typed_id::SessionId,
    name: &str,
    task_id: &Option<String>,
    blueprint_param: &Option<String>,
) -> ToolExecutionResult {
    ToolExecutionResult::success(json!({
        "subagent_id": child_id.to_string(),
        "name": name,
        "status": "running",
        "mode": "background",
        "task_id": task_id,
        "blueprint": blueprint_param,
        "message": "Subagent started in the background. Monitor it with get_task or wait_task using task_id; the session is notified when it finishes.",
    }))
}

// =============================================================================
// Helpers for SpawnSubagentTool
// =============================================================================

/// Create a new child session, then either wait for completion (foreground)
/// or detach a watcher and return immediately (background). Settles the spawn
/// handle (if a settle context is supplied) when the child reaches a terminal
/// state.
///
/// `settle_ctx` = (spawn_store, tool_call_id, spawn_handle_id, claim_token).
/// `spawn_handle_id` is used to call `register_child_session` after child creation.
#[allow(clippy::too_many_arguments)]
async fn spawn_create_and_wait(
    store: &dyn PlatformStore,
    context: &ToolContext,
    parent_session: &crate::session::Session,
    name: &str,
    instructions: &str,
    blueprint_param: &Option<String>,
    config_param: &Option<Value>,
    mode: SpawnMode,
    settle_ctx: Option<(
        &dyn crate::traits::SubagentSpawnStore,
        &str,
        uuid::Uuid,
        uuid::Uuid,
    )>,
) -> ToolExecutionResult {
    // Create child session, linking it to the parent (nesting guard).
    let child_session = match store
        .create_session(
            parent_session.harness_id,
            if blueprint_param.is_some() {
                None // Blueprint sessions don't inherit agent
            } else {
                parent_session.agent_id
            },
            Some(name),
            parent_session.locale.as_deref(),
            blueprint_param.as_deref(),
            config_param.as_ref(),
            Some(context.session_id),
        )
        .await
    {
        Ok(s) => s,
        Err(e) => return ToolExecutionResult::internal_error(e),
    };
    // Create the session task tracking this subagent (specs/session-tasks.md).
    // Background tasks wake the parent on terminal transition through the
    // registry-level wake policy; foreground spawns already return the result
    // inline, so a wake would be noise.
    let mut task_id: Option<String> = None;
    let mut task_attempt: i32 = 1;
    if let Some(ref task_registry) = context.session_task_registry
        && let Ok(created) = task_registry
            .create(CreateSessionTask {
                session_id: context.session_id,
                id: None,
                kind: TASK_KIND_SUBAGENT.to_string(),
                display_name: name.to_string(),
                spec: json!({
                    "instructions": instructions,
                    "blueprint_id": blueprint_param,
                    "mode": mode.as_str(),
                }),
                state: SessionTaskState::Running,
                links: TaskLinks {
                    child_session_id: Some(child_session.id),
                    ..Default::default()
                },
                wake_policy: match mode {
                    SpawnMode::Background => TaskWakePolicy::OnTerminal,
                    SpawnMode::Foreground => TaskWakePolicy::Silent,
                },
            })
            .await
    {
        task_id = Some(created.id);
        task_attempt = created.attempt;
    }

    // Register child session ID durably BEFORE waiting.
    // This is the durability boundary: once registered, a reclaim/replay can
    // reattach to this child instead of spawning another.
    let wait_settle_ctx = if let Some((spawn_store, tool_call_id, spawn_handle_id, claim_token)) =
        settle_ctx
    {
        if let Err(e) = spawn_store
            .register_child_session(spawn_handle_id, claim_token, child_session.id)
            .await
        {
            tracing::warn!(
                tool_call_id,
                error = %e,
                "Failed to register child session in spawn handle; proceeding without durable reattach"
            );
        }
        Some((spawn_store, tool_call_id, claim_token))
    } else {
        None
    };

    if mode == SpawnMode::Background {
        // The first message is sent inside the watcher: local/embedded hosts
        // (everruns-runtime) run the child's turn synchronously inside
        // send_message, so sending here would block the spawn call.
        spawn_background_watcher(
            context,
            child_session.id,
            name,
            Some(instructions.to_string()),
            task_id.clone(),
            task_attempt,
            wait_settle_ctx.map(|(_, _, claim_token)| claim_token),
        );
        return background_running_result(child_session.id, name, &task_id, blueprint_param);
    }

    // Send the instructions as the first message
    if let Err(e) = store.send_message(child_session.id, instructions).await {
        finish_subagent_task(
            context,
            task_id.as_deref(),
            SessionTaskState::Failed,
            None,
            Some(TaskError {
                kind: "error".to_string(),
                message: e.to_string(),
            }),
        )
        .await;
        return ToolExecutionResult::internal_error(e);
    }

    run_subagent_wait_and_settle(
        store,
        context,
        child_session.id,
        name,
        instructions,
        blueprint_param,
        task_id,
        wait_settle_ctx,
    )
    .await
}

/// Wait for a child session to reach idle, collect its result, update the
/// registry, and settle the spawn handle (if a settle context is supplied).
#[allow(clippy::too_many_arguments)]
async fn run_subagent_wait_and_settle(
    store: &dyn PlatformStore,
    context: &ToolContext,
    child_id: crate::typed_id::SessionId,
    name: &str,
    _instructions: &str,
    blueprint_param: &Option<String>,
    task_id: Option<String>,
    settle_ctx: Option<(&dyn crate::traits::SubagentSpawnStore, &str, uuid::Uuid)>,
) -> ToolExecutionResult {
    // Foreground mode: wait for completion
    let status = match store.wait_for_idle(child_id, Some(300)).await {
        Ok(s) => s,
        Err(e) => {
            finish_subagent_task(
                context,
                task_id.as_deref(),
                SessionTaskState::Failed,
                None,
                Some(TaskError {
                    kind: "error".to_string(),
                    message: e.to_string(),
                }),
            )
            .await;
            return ToolExecutionResult::success(json!({
                "subagent_id": child_id.to_string(),
                "name": name,
                "status": "failed",
                "error": e.to_string(),
                "task_id": task_id,
                "blueprint": blueprint_param,
            }));
        }
    };

    let result_text = match settle_subagent_outcome(
        store,
        context,
        child_id,
        &status,
        task_id.as_deref(),
        settle_ctx,
    )
    .await
    {
        Ok(text) => text,
        Err(error) => return error,
    };

    ToolExecutionResult::success(json!({
        "subagent_id": child_id.to_string(),
        "name": name,
        "status": status,
        "result": result_text,
        "task_id": task_id,
        "blueprint": blueprint_param,
    }))
}

/// Collect the child's final message and, when `status` is terminal, settle
/// the spawn handle and mirror the outcome onto the session task. Non-terminal
/// statuses (paused, waiting_for_tool_results, timeout) only produce the
/// result text — the child stays active and the spawn stays reattachable.
async fn settle_subagent_outcome(
    store: &dyn PlatformStore,
    context: &ToolContext,
    child_id: crate::typed_id::SessionId,
    status: &str,
    task_id: Option<&str>,
    settle_ctx: Option<(&dyn crate::traits::SubagentSpawnStore, &str, uuid::Uuid)>,
) -> Result<String, ToolExecutionResult> {
    // Get the subagent's response messages
    let messages = match store.get_messages(child_id, Some(5)).await {
        Ok(m) => m,
        Err(e) => return Err(ToolExecutionResult::internal_error(e)),
    };

    let result_text = last_agent_message(&messages)
        .unwrap_or_else(|| format!("Subagent completed with status: {status}"));

    let terminal_status = terminal_subagent_status(status);

    // Settle the spawn handle only when the child reached a terminal state.
    // Non-terminal waits must stay reattachable on replay.
    if let Some((spawn_store, tool_call_id, claim_token)) = settle_ctx
        && terminal_status.is_some()
        && let Err(e) = spawn_store
            .settle_spawn(
                context.session_id,
                tool_call_id,
                claim_token,
                status,
                &result_text,
            )
            .await
    {
        // Best-effort: log but don't fail the tool execution.
        tracing::warn!(
            tool_call_id,
            error = %e,
            "Failed to settle subagent spawn handle"
        );
    }

    // Update the session task only when the child reached a terminal state.
    if let Some(subagent_status) = terminal_status {
        let task_state = terminal_subagent_task_state(&subagent_status);
        let task_error = if task_state == SessionTaskState::Failed {
            Some(TaskError {
                kind: status.to_string(),
                message: format!("Subagent session ended with status: {status}"),
            })
        } else {
            None
        };
        finish_subagent_task(
            context,
            task_id,
            task_state,
            Some(truncate_summary(&result_text)),
            task_error,
        )
        .await;
    }

    Ok(result_text)
}

/// Detach a watcher that drives a background subagent to completion: send the
/// first message (fresh spawns only), heartbeat the task registry so the
/// reaper can detect worker loss, wait for the child's terminal turn status,
/// then settle the task and spawn handle. The task's OnTerminal wake policy
/// notifies the parent session at the registry level.
fn spawn_background_watcher(
    context: &ToolContext,
    child_id: crate::typed_id::SessionId,
    name: &str,
    first_message: Option<String>,
    task_id: Option<String>,
    task_attempt: i32,
    claim_token: Option<uuid::Uuid>,
) {
    let context = context.clone();
    let name = name.to_string();
    tokio::spawn(async move {
        let Some(store) = context.platform_store.clone() else {
            // Callers only enter background mode with a platform store wired.
            return;
        };

        if let Some(instructions) = first_message
            && let Err(e) = store.send_message(child_id, &instructions).await
        {
            finish_subagent_task(
                &context,
                task_id.as_deref(),
                SessionTaskState::Failed,
                None,
                Some(TaskError {
                    kind: "error".to_string(),
                    message: e.to_string(),
                }),
            )
            .await;
            return;
        }

        // Heartbeat so the session task reaper can fail an orphaned watcher
        // (worker loss) instead of leaving the task running forever. Fenced on
        // the attempt captured at spawn so a superseded watcher's writes are
        // rejected once the reaper bumps the attempt counter.
        let heartbeat = async {
            let (Some(registry), Some(task_id)) =
                (context.session_task_registry.clone(), task_id.clone())
            else {
                return std::future::pending::<()>().await;
            };
            loop {
                tokio::time::sleep(std::time::Duration::from_secs(
                    BACKGROUND_HEARTBEAT_INTERVAL_SECS,
                ))
                .await;
                let _ = registry
                    .update(
                        context.session_id,
                        &task_id,
                        SessionTaskUpdate {
                            heartbeat_at: Some(chrono::Utc::now()),
                            expected_attempt: Some(task_attempt),
                            ..Default::default()
                        },
                    )
                    .await;
            }
        };

        let wait_and_settle = async {
            let started = tokio::time::Instant::now();
            loop {
                let status = match store
                    .wait_for_idle(child_id, Some(BACKGROUND_WAIT_SLICE_SECS))
                    .await
                {
                    Ok(s) => s,
                    Err(e) => {
                        finish_subagent_task(
                            &context,
                            task_id.as_deref(),
                            SessionTaskState::Failed,
                            None,
                            Some(TaskError {
                                kind: "error".to_string(),
                                message: e.to_string(),
                            }),
                        )
                        .await;
                        return;
                    }
                };

                // Local/embedded hosts (everruns-runtime) run the child's turn
                // synchronously inside send_message and report a bare `idle`;
                // hosted adapters never return it (they poll until a terminal
                // turn event lands). Map it to completion so embedder tasks
                // settle instead of looping until the cap.
                let effective = if status == "idle" {
                    "completed".to_string()
                } else {
                    status
                };

                if terminal_subagent_status(&effective).is_some() {
                    let settle_ctx = match (
                        context.subagent_spawn_store.as_ref(),
                        context.tool_call_id.as_ref(),
                        claim_token,
                    ) {
                        (Some(spawn_store), Some(tool_call_id), Some(token)) => Some((
                            spawn_store.as_ref() as &dyn crate::traits::SubagentSpawnStore,
                            tool_call_id.as_str(),
                            token,
                        )),
                        _ => None,
                    };
                    if let Err(error) = settle_subagent_outcome(
                        store.as_ref(),
                        &context,
                        child_id,
                        &effective,
                        task_id.as_deref(),
                        settle_ctx,
                    )
                    .await
                    {
                        tracing::warn!(
                            subagent_name = name,
                            child_session_id = %child_id,
                            ?error,
                            "Background subagent settle failed; marking task failed"
                        );
                        finish_subagent_task(
                            &context,
                            task_id.as_deref(),
                            SessionTaskState::Failed,
                            None,
                            Some(TaskError {
                                kind: "error".to_string(),
                                message: "Failed to read subagent result".to_string(),
                            }),
                        )
                        .await;
                    }
                    return;
                }

                if started.elapsed().as_secs() >= BACKGROUND_MAX_WAIT_SECS {
                    finish_subagent_task(
                        &context,
                        task_id.as_deref(),
                        SessionTaskState::Failed,
                        None,
                        Some(TaskError {
                            kind: "timeout".to_string(),
                            message: format!(
                                "Background subagent did not finish within {BACKGROUND_MAX_WAIT_SECS}s (last status: {effective})"
                            ),
                        }),
                    )
                    .await;
                    return;
                }

                // Non-terminal: record progress and keep waiting. Statuses
                // other than the wait-slice timeout return immediately, so
                // back off before re-waiting to avoid spinning.
                if let (Some(registry), Some(task_id)) =
                    (context.session_task_registry.as_ref(), task_id.as_deref())
                {
                    let _ = registry
                        .update(
                            context.session_id,
                            task_id,
                            SessionTaskUpdate {
                                state_detail: Some(format!(
                                    "waiting for subagent ({}s elapsed, last status: {effective})",
                                    started.elapsed().as_secs()
                                )),
                                expected_attempt: Some(task_attempt),
                                ..Default::default()
                            },
                        )
                        .await;
                }
                if !effective.starts_with("timeout") {
                    tokio::time::sleep(std::time::Duration::from_secs(
                        BACKGROUND_POLL_BACKOFF_SECS,
                    ))
                    .await;
                }
            }
        };

        tokio::select! {
            () = wait_and_settle => {}
            () = heartbeat => {}
        }
    });
}

// =============================================================================
// Task executor: subagent
// =============================================================================

/// Control plane for `subagent` tasks. Inbound messages and cooperative
/// cancellation route through the child session's message channel — there is
/// no hard kill, so cancel delivers a graceful stop request via `cancel_task`.
pub struct SubagentTaskExecutor;

#[async_trait]
impl TaskExecutor for SubagentTaskExecutor {
    fn kind(&self) -> &str {
        TASK_KIND_SUBAGENT
    }

    async fn deliver(
        &self,
        task: &SessionTask,
        message: &TaskMessage,
        context: &ToolContext,
    ) -> crate::error::Result<()> {
        let Some(store) = context.platform_store.as_ref() else {
            return Err(crate::error::AgentLoopError::tool(
                "subagent task delivery requires platform_store context",
            ));
        };
        let Some(child_id) = task.links.child_session_id else {
            return Err(crate::error::AgentLoopError::tool(format!(
                "subagent task {} has no child session link",
                task.id
            )));
        };
        let text = task_message_text(&message.content);
        store.send_message(child_id, &text).await
    }

    async fn cancel(&self, task: &SessionTask, context: &ToolContext) -> crate::error::Result<()> {
        let Some(store) = context.platform_store.as_ref() else {
            return Err(crate::error::AgentLoopError::tool(
                "subagent task cancellation requires platform_store context",
            ));
        };
        let Some(child_id) = task.links.child_session_id else {
            return Err(crate::error::AgentLoopError::tool(format!(
                "subagent task {} has no child session link",
                task.id
            )));
        };
        // Graceful stop request; takes effect after the current turn.
        store
            .send_message(
                child_id,
                "Cancellation requested by the parent session. Stop work, wind down, and reply with a brief summary of progress so far.",
            )
            .await
    }

    /// Converge a subagent task whose background watcher is gone (worker
    /// loss): probe the child's terminal turn status and mirror it onto the
    /// task. Called from wait_task's poll loop; no-op while the child is
    /// still working.
    async fn reconcile(
        &self,
        task: &SessionTask,
        context: &ToolContext,
    ) -> crate::error::Result<()> {
        if task.state.is_terminal() {
            return Ok(());
        }
        let (Some(store), Some(child_id)) =
            (context.platform_store.as_ref(), task.links.child_session_id)
        else {
            return Ok(());
        };
        // Zero-timeout probe: returns the terminal turn status when the child
        // already finished, or a timeout marker while it is still running.
        let status = store.wait_for_idle(child_id, Some(0)).await?;
        if terminal_subagent_status(&status).is_none() {
            return Ok(());
        }
        settle_subagent_outcome(
            store.as_ref(),
            context,
            child_id,
            &status,
            Some(&task.id),
            None,
        )
        .await
        .map(|_| ())
        .map_err(|_| {
            crate::error::AgentLoopError::tool("Failed to read subagent result during reconcile")
        })
    }
}

inventory::submit! {
    TaskExecutorPlugin {
        executor: || Arc::new(SubagentTaskExecutor),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Tool;

    // Metadata/tool-list constants covered by builtin_capabilities_satisfy_registry_invariants.

    #[test]
    fn capability_features() {
        let cap = SubagentCapability;
        assert_eq!(cap.features(), vec!["subagents"]);
    }

    #[test]
    fn terminal_subagent_status_maps_only_terminal_wait_states() {
        // `idle` is not terminal: a failed turn also idles the worker, so it
        // must not settle the subagent as completed.
        assert_eq!(terminal_subagent_status("idle"), None);
        assert_eq!(
            terminal_subagent_status("completed"),
            Some(crate::session::SubagentStatus::Completed)
        );
        assert_eq!(
            terminal_subagent_status("failed"),
            Some(crate::session::SubagentStatus::Failed)
        );
        assert_eq!(
            terminal_subagent_status("cancelled"),
            Some(crate::session::SubagentStatus::Cancelled)
        );
        assert_eq!(
            terminal_subagent_status("sealed"),
            Some(crate::session::SubagentStatus::Sealed)
        );
        assert_eq!(
            terminal_subagent_task_state(&crate::session::SubagentStatus::Completed),
            SessionTaskState::Succeeded
        );
        // A sealed subagent settles as a terminal, non-retryable failed task.
        assert_eq!(
            terminal_subagent_task_state(&crate::session::SubagentStatus::Sealed),
            SessionTaskState::Failed
        );
        assert_eq!(
            terminal_subagent_task_state(&crate::session::SubagentStatus::Cancelled),
            SessionTaskState::Canceled
        );
        assert_eq!(
            terminal_subagent_task_state(&crate::session::SubagentStatus::MaxIterationsReached),
            SessionTaskState::Failed
        );
        assert_eq!(terminal_subagent_status("waiting_for_tool_results"), None);
        assert_eq!(terminal_subagent_status("paused"), None);
    }

    #[test]
    fn spawn_subagent_schema_has_required_fields() {
        let tool = SpawnSubagentTool;
        let schema = tool.parameters_schema();
        let required = schema["required"].as_array().unwrap();
        assert!(required.contains(&json!("name")));
        assert!(required.contains(&json!("instructions")));
    }

    #[test]
    fn spawn_subagent_schema_has_blueprint_fields() {
        let tool = SpawnSubagentTool;
        let schema = tool.parameters_schema();
        let props = schema["properties"].as_object().unwrap();
        assert!(props.contains_key("blueprint"));
        assert!(props.contains_key("config"));
        // blueprint and config should NOT be required
        let required = schema["required"].as_array().unwrap();
        assert!(!required.contains(&json!("blueprint")));
        assert!(!required.contains(&json!("config")));
    }

    #[test]
    fn spawn_subagent_schema_has_optional_mode_enum() {
        let tool = SpawnSubagentTool;
        let schema = tool.parameters_schema();
        let mode = &schema["properties"]["mode"];
        assert_eq!(mode["type"], "string");
        assert_eq!(mode["enum"], json!(["background", "foreground"]));
        let required = schema["required"].as_array().unwrap();
        assert!(!required.contains(&json!("mode")));
    }

    #[tokio::test]
    async fn spawn_subagent_without_context_returns_error() {
        let tool = SpawnSubagentTool;
        let result = tool
            .execute(json!({"name": "Test", "instructions": "test"}))
            .await;
        assert!(matches!(result, ToolExecutionResult::ToolError(_)));
    }

    // =========================================================================
    // Spawn handle tests (EVE-535)
    // =========================================================================

    use crate::traits::{NoopSubagentSpawnStore, SpawnClaimResult, SubagentSpawnStore};
    use std::sync::Arc;

    /// NoopSubagentSpawnStore always returns Claimed with a fresh token.
    #[tokio::test]
    async fn noop_spawn_store_always_claims() {
        let store = NoopSubagentSpawnStore;
        let parent = crate::typed_id::SessionId::new();
        let token = uuid::Uuid::new_v4();

        let result = store
            .try_claim_spawn(parent, "call-1", token)
            .await
            .expect("noop should not error");

        assert!(
            matches!(result, SpawnClaimResult::Claimed { claim_token, .. } if claim_token == token),
            "noop store should return Claimed with the supplied token"
        );
    }

    /// NoopSubagentSpawnStore register and settle are always successful.
    #[tokio::test]
    async fn noop_spawn_store_register_and_settle_are_noops() {
        let store = NoopSubagentSpawnStore;
        let parent = crate::typed_id::SessionId::new();
        let child = crate::typed_id::SessionId::new();
        let handle_id = uuid::Uuid::new_v4();
        let token = uuid::Uuid::new_v4();

        store
            .register_child_session(handle_id, token, child)
            .await
            .expect("noop register should not error");

        store
            .settle_spawn(parent, "call-1", token, "idle", "result text")
            .await
            .expect("noop settle should not error");
    }

    /// Arc<dyn SubagentSpawnStore> blanket impl delegates correctly.
    #[tokio::test]
    async fn arc_spawn_store_delegates() {
        let store: Arc<dyn SubagentSpawnStore> = Arc::new(NoopSubagentSpawnStore);
        let parent = crate::typed_id::SessionId::new();
        let token = uuid::Uuid::new_v4();

        let result = store
            .try_claim_spawn(parent, "call-arc", token)
            .await
            .expect("arc delegation should not error");

        assert!(matches!(result, SpawnClaimResult::Claimed { .. }));
    }

    // =========================================================================
    // Background mode
    // =========================================================================

    use crate::capabilities::session_tasks::tests::InMemorySessionTaskRegistry;
    use crate::platform_store::tests::MockPlatformStore;
    use crate::session_task::SessionTaskRegistry;

    /// SessionStore view over the mock platform store (nesting guard lookup).
    struct MockSessionStore(Arc<MockPlatformStore>);

    #[async_trait]
    impl crate::traits::SessionStore for MockSessionStore {
        async fn get_session(
            &self,
            session_id: crate::typed_id::SessionId,
        ) -> crate::error::Result<Option<crate::session::Session>> {
            self.0.get_session_by_id(session_id).await
        }
    }

    fn spawn_context(
        store: &Arc<MockPlatformStore>,
        registry: Option<Arc<InMemorySessionTaskRegistry>>,
    ) -> ToolContext {
        let mut context = ToolContext::new(store.session.id);
        context.platform_store = Some(store.clone());
        context.session_store = Some(Arc::new(MockSessionStore(store.clone())));
        if let Some(registry) = registry {
            context.session_task_registry = Some(registry);
        }
        context
    }

    async fn spawn(context: &ToolContext, args: Value) -> ToolExecutionResult {
        SpawnSubagentTool.execute_with_context(args, context).await
    }

    /// Poll the registry until the subagent task reaches `state` (the
    /// background watcher settles it from a detached tokio task).
    async fn wait_for_task_state(
        registry: &InMemorySessionTaskRegistry,
        session_id: crate::typed_id::SessionId,
        task_id: &str,
        state: crate::session_task::SessionTaskState,
    ) -> crate::session_task::SessionTask {
        for _ in 0..200 {
            let task = registry
                .get(session_id, task_id)
                .await
                .expect("registry get")
                .expect("task exists");
            if task.state == state {
                return task;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        panic!("task {task_id} did not reach {state:?}");
    }

    #[tokio::test]
    async fn spawn_subagent_rejects_invalid_mode() {
        let context = ToolContext::new(crate::typed_id::SessionId::new());
        let result = spawn(
            &context,
            json!({"name": "Runner", "instructions": "go", "mode": "asap"}),
        )
        .await;
        let ToolExecutionResult::ToolError(msg) = result else {
            panic!("expected ToolError, got {result:?}");
        };
        assert!(msg.contains("Invalid mode"), "got: {msg}");
    }

    #[tokio::test]
    async fn explicit_background_without_registry_errors() {
        let context = ToolContext::new(crate::typed_id::SessionId::new());
        let result = spawn(
            &context,
            json!({"name": "Runner", "instructions": "go", "mode": "background"}),
        )
        .await;
        let ToolExecutionResult::ToolError(msg) = result else {
            panic!("expected ToolError, got {result:?}");
        };
        assert!(
            msg.contains("task registry") && msg.contains("foreground"),
            "got: {msg}"
        );
    }

    #[tokio::test]
    async fn default_mode_without_registry_degrades_to_foreground() {
        let store = Arc::new(MockPlatformStore::new());
        let context = spawn_context(&store, None);
        let result = spawn(&context, json!({"name": "Runner", "instructions": "go"})).await;
        let ToolExecutionResult::Success(value) = result else {
            panic!("expected success, got {result:?}");
        };
        // Foreground semantics: waited inline and returned the child's reply.
        assert_eq!(value["status"], "idle");
        assert_eq!(value["result"], "Hi!");
        assert!(value.get("mode").is_none());
    }

    #[tokio::test]
    async fn background_spawn_returns_immediately_and_settles_task() {
        let store = Arc::new(MockPlatformStore::new());
        *store.wait_for_idle_status.lock().unwrap() = "completed".to_string();
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let result = spawn(&context, json!({"name": "Runner", "instructions": "go"})).await;
        let ToolExecutionResult::Success(value) = result else {
            panic!("expected success, got {result:?}");
        };
        assert_eq!(value["status"], "running");
        assert_eq!(value["mode"], "background");
        let task_id = value["task_id"].as_str().expect("task_id").to_string();

        let task = wait_for_task_state(
            &registry,
            context.session_id,
            &task_id,
            SessionTaskState::Succeeded,
        )
        .await;
        // Background tasks wake the parent on terminal transition.
        assert_eq!(task.wake_policy, TaskWakePolicy::OnTerminal);
        assert_eq!(task.spec["mode"], "background");
        // Summary carries the child's last agent message.
        assert_eq!(task.summary.as_deref(), Some("Hi!"));
    }

    #[tokio::test]
    async fn background_settles_bare_idle_as_completed() {
        // Local/embedded hosts run the child's turn synchronously inside
        // send_message and report a bare `idle`; the watcher must settle it.
        let store = Arc::new(MockPlatformStore::new());
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let result = spawn(&context, json!({"name": "Runner", "instructions": "go"})).await;
        let ToolExecutionResult::Success(value) = result else {
            panic!("expected success, got {result:?}");
        };
        let task_id = value["task_id"].as_str().expect("task_id").to_string();
        wait_for_task_state(
            &registry,
            context.session_id,
            &task_id,
            SessionTaskState::Succeeded,
        )
        .await;
    }

    #[tokio::test]
    async fn background_failed_child_settles_task_failed() {
        let store = Arc::new(MockPlatformStore::new());
        *store.wait_for_idle_status.lock().unwrap() = "failed".to_string();
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let result = spawn(&context, json!({"name": "Runner", "instructions": "go"})).await;
        let ToolExecutionResult::Success(value) = result else {
            panic!("expected success, got {result:?}");
        };
        let task_id = value["task_id"].as_str().expect("task_id").to_string();
        let task = wait_for_task_state(
            &registry,
            context.session_id,
            &task_id,
            SessionTaskState::Failed,
        )
        .await;
        assert_eq!(task.error.as_ref().map(|e| e.kind.as_str()), Some("failed"));
    }

    #[tokio::test]
    async fn explicit_foreground_blocks_and_returns_result() {
        let store = Arc::new(MockPlatformStore::new());
        *store.wait_for_idle_status.lock().unwrap() = "completed".to_string();
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let result = spawn(
            &context,
            json!({"name": "Runner", "instructions": "go", "mode": "foreground"}),
        )
        .await;
        let ToolExecutionResult::Success(value) = result else {
            panic!("expected success, got {result:?}");
        };
        assert_eq!(value["status"], "completed");
        assert_eq!(value["result"], "Hi!");
        // Foreground spawn settles the task before returning.
        let task_id = value["task_id"].as_str().expect("task_id");
        let task = registry
            .get(context.session_id, task_id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(task.state, SessionTaskState::Succeeded);
        assert_eq!(task.wake_policy, TaskWakePolicy::Silent);
    }

    #[tokio::test]
    async fn reconcile_settles_finished_child() {
        let store = Arc::new(MockPlatformStore::new());
        *store.wait_for_idle_status.lock().unwrap() = "completed".to_string();
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let child_id = crate::typed_id::SessionId::new();
        let task = registry
            .create(CreateSessionTask {
                session_id: context.session_id,
                id: None,
                kind: TASK_KIND_SUBAGENT.to_string(),
                display_name: "Runner".to_string(),
                spec: json!({"mode": "background"}),
                state: SessionTaskState::Running,
                links: TaskLinks {
                    child_session_id: Some(child_id),
                    ..Default::default()
                },
                wake_policy: TaskWakePolicy::OnTerminal,
            })
            .await
            .unwrap();

        SubagentTaskExecutor
            .reconcile(&task, &context)
            .await
            .expect("reconcile succeeds");

        let task = registry
            .get(context.session_id, &task.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(task.state, SessionTaskState::Succeeded);
        assert_eq!(task.summary.as_deref(), Some("Hi!"));
    }

    #[tokio::test]
    async fn reconcile_is_noop_while_child_still_working() {
        let store = Arc::new(MockPlatformStore::new());
        *store.wait_for_idle_status.lock().unwrap() = "timeout (last status: Active)".to_string();
        let registry = Arc::new(InMemorySessionTaskRegistry::default());
        let context = spawn_context(&store, Some(registry.clone()));

        let task = registry
            .create(CreateSessionTask {
                session_id: context.session_id,
                id: None,
                kind: TASK_KIND_SUBAGENT.to_string(),
                display_name: "Runner".to_string(),
                spec: json!({"mode": "background"}),
                state: SessionTaskState::Running,
                links: TaskLinks {
                    child_session_id: Some(crate::typed_id::SessionId::new()),
                    ..Default::default()
                },
                wake_policy: TaskWakePolicy::OnTerminal,
            })
            .await
            .unwrap();

        SubagentTaskExecutor
            .reconcile(&task, &context)
            .await
            .expect("reconcile succeeds");

        let task = registry
            .get(context.session_id, &task.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(task.state, SessionTaskState::Running);
    }
}