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
// AHP Hook Executor Implementation
//
// Bridges A3S Code's hook system with AHP protocol
use crate::hooks::{HookEvent, HookEventType, HookExecutor, HookResult};
use a3s_ahp::protocol::{
ConfirmationDecision, ContextPerceptionDecision, IntentDetectionDecision, MemoryRecallDecision,
PlanningDecision, RateLimitDecision, ReasoningDecision,
};
use a3s_ahp::{
AhpClient, AhpEvent, Decision, EventType, HeartbeatEvent, IdleEvent, SessionStats, Transport,
};
use async_trait::async_trait;
use chrono::Utc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use tracing::{debug, warn};
/// AHP Hook Executor
///
/// Implements `HookExecutor` trait to forward A3S Code hook events
/// to an external AHP harness server for supervision.
#[derive(Clone)]
pub struct AhpHookExecutor {
client: Arc<AhpClient>,
agent_id: String,
depth: u32,
/// Last activity timestamp for idle detection
last_activity: Arc<AtomicU64>,
/// Idle threshold in milliseconds - fire Idle event after this duration of inactivity
idle_threshold_ms: u64,
/// Start time of the executor
start_time: Instant,
/// Total events processed
total_events: Arc<AtomicU64>,
/// Total tokens used (updated from PostResponse events)
total_tokens: Arc<AtomicI32>,
/// Error count for session stats
error_count: Arc<AtomicU64>,
/// Client自主 exposes capabilities for the server to use
capabilities: HashMap<String, serde_json::Value>,
/// Shutdown signal for background tasks
shutdown: Arc<AtomicBool>,
/// Memory summary for context (set via set_memory_summary)
memory_summary: Arc<RwLock<Option<a3s_ahp::MemorySummary>>>,
/// Current task description for context (set via set_current_task)
current_task: Arc<RwLock<Option<String>>>,
/// Recent facts for context (set via add_recent_fact)
recent_facts: Arc<RwLock<Vec<a3s_ahp::Fact>>>,
/// Current workspace path (set via set_workspace)
workspace: Arc<RwLock<Option<String>>>,
/// Batch accumulator for non-blocking events
batch_buffer: Arc<RwLock<Vec<a3s_ahp::AhpEvent>>>,
/// Batch size threshold (default 10)
batch_size: usize,
/// Batch flush timeout in milliseconds (default 5000)
batch_timeout_ms: u64,
/// Last batch flush timestamp
last_batch_flush: Arc<AtomicU64>,
/// Enable batch processing
batch_enabled: bool,
}
impl std::fmt::Debug for AhpHookExecutor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AhpHookExecutor")
.field("agent_id", &self.agent_id)
.field("depth", &self.depth)
.field("idle_threshold_ms", &self.idle_threshold_ms)
.finish()
}
}
impl AhpHookExecutor {
/// Create a new AHP hook executor
///
/// # Arguments
///
/// * `transport` - AHP transport (stdio, HTTP, WebSocket)
///
/// # Example
///
/// ```rust,no_run
/// use a3s_code_core::ahp::{AhpHookExecutor, AhpTransport};
///
/// # async fn example() -> anyhow::Result<()> {
/// let executor = AhpHookExecutor::new(
/// AhpTransport::http("http://localhost:8080/ahp", None)
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn new(transport: Transport) -> Result<Self, a3s_ahp::AhpError> {
Self::new_with_config(transport, 10_000).await // Default 10s idle threshold
}
/// Create with custom idle threshold
pub async fn new_with_config(
transport: Transport,
idle_threshold_ms: u64,
) -> Result<Self, a3s_ahp::AhpError> {
let client = AhpClient::new(transport).await?;
// Build full capability list for handshake
let capabilities = vec![
"pre_action".to_string(),
"post_action".to_string(),
"pre_prompt".to_string(),
"post_response".to_string(),
"session_start".to_string(),
"session_end".to_string(),
"error".to_string(),
"context_perception".to_string(),
"success".to_string(),
"memory_recall".to_string(),
"planning".to_string(),
"reasoning".to_string(),
"rate_limit".to_string(),
"confirmation".to_string(),
"idle".to_string(),
"heartbeat".to_string(),
"query".to_string(),
"batch".to_string(),
"skill_load".to_string(),
"skill_unload".to_string(),
];
// Perform handshake with capabilities
client.handshake(capabilities.clone()).await?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
Ok(Self {
client: Arc::new(client),
agent_id: uuid::Uuid::new_v4().to_string(),
depth: 0,
last_activity: Arc::new(AtomicU64::new(now)),
idle_threshold_ms,
start_time: Instant::now(),
total_events: Arc::new(AtomicU64::new(0)),
total_tokens: Arc::new(AtomicI32::new(0)),
error_count: Arc::new(AtomicU64::new(0)),
capabilities: HashMap::new(),
shutdown: Arc::new(AtomicBool::new(false)),
memory_summary: Arc::new(RwLock::new(None)),
current_task: Arc::new(RwLock::new(None)),
recent_facts: Arc::new(RwLock::new(Vec::new())),
workspace: Arc::new(RwLock::new(None)),
batch_buffer: Arc::new(RwLock::new(Vec::new())),
batch_size: 10,
batch_timeout_ms: 5000,
last_batch_flush: Arc::new(AtomicU64::new(now)),
batch_enabled: false,
})
}
/// Create a new executor for testing with a pre-configured client.
///
/// This bypasses the handshake step, allowing integration tests to use
/// a mock transport without requiring a running AHP server.
///
/// # Arguments
///
/// * `client` - Pre-configured AhpClient (typically with a mock transport)
/// * `idle_threshold_ms` - Idle threshold in milliseconds
///
/// # Example
///
/// ```rust,ignore
/// use a3s_ahp::transport::TransportLayer;
///
/// let mock_transport = MockTransport::new();
/// let client = AhpClient::new_for_testing(Arc::new(mock_transport));
/// let executor = AhpHookExecutor::new_for_testing(client, 10_000);
/// ```
pub fn new_for_testing(client: Arc<AhpClient>, idle_threshold_ms: u64) -> Self {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
Self {
client,
agent_id: uuid::Uuid::new_v4().to_string(),
depth: 0,
last_activity: Arc::new(AtomicU64::new(now)),
idle_threshold_ms,
start_time: Instant::now(),
total_events: Arc::new(AtomicU64::new(0)),
total_tokens: Arc::new(AtomicI32::new(0)),
error_count: Arc::new(AtomicU64::new(0)),
capabilities: HashMap::new(),
shutdown: Arc::new(AtomicBool::new(false)),
memory_summary: Arc::new(RwLock::new(None)),
current_task: Arc::new(RwLock::new(None)),
recent_facts: Arc::new(RwLock::new(Vec::new())),
workspace: Arc::new(RwLock::new(None)),
batch_buffer: Arc::new(RwLock::new(Vec::new())),
batch_size: 10,
batch_timeout_ms: 5000,
last_batch_flush: Arc::new(AtomicU64::new(now)),
batch_enabled: false,
}
}
/// Create with specific agent ID and depth
pub async fn with_context(
transport: Transport,
agent_id: String,
depth: u32,
) -> Result<Self, a3s_ahp::AhpError> {
Self::with_context_and_config(transport, agent_id, depth, 10_000).await
}
/// Create with specific agent ID, depth, and custom idle threshold
pub async fn with_context_and_config(
transport: Transport,
agent_id: String,
depth: u32,
idle_threshold_ms: u64,
) -> Result<Self, a3s_ahp::AhpError> {
let client = AhpClient::new(transport).await?;
// For testing: pass minimal capabilities
client
.handshake(vec!["pre_action".to_string(), "post_action".to_string()])
.await?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
Ok(Self {
client: Arc::new(client),
agent_id,
depth,
last_activity: Arc::new(AtomicU64::new(now)),
idle_threshold_ms,
start_time: Instant::now(),
total_events: Arc::new(AtomicU64::new(0)),
total_tokens: Arc::new(AtomicI32::new(0)),
error_count: Arc::new(AtomicU64::new(0)),
capabilities: HashMap::new(),
shutdown: Arc::new(AtomicBool::new(false)),
memory_summary: Arc::new(RwLock::new(None)),
current_task: Arc::new(RwLock::new(None)),
recent_facts: Arc::new(RwLock::new(Vec::new())),
workspace: Arc::new(RwLock::new(None)),
batch_buffer: Arc::new(RwLock::new(Vec::new())),
batch_size: 10,
batch_timeout_ms: 5000,
last_batch_flush: Arc::new(AtomicU64::new(now)),
batch_enabled: false,
})
}
/// Builder method to add client自主 exposes capabilities.
///
/// Capabilities allow the server to interact with the agent by calling
/// exposed functions/URLs. Common capabilities:
/// - `memory_search`: Search across memories
/// - `session_info`: Get current session information
/// - `cross_session`: Query cross-session data
///
/// # Example
///
/// ```rust,no_run
/// use a3s_code_core::ahp::{AhpHookExecutor, AhpTransport};
///
/// # async fn example() -> anyhow::Result<()> {
/// let executor = AhpHookExecutor::new(
/// AhpTransport::http("http://localhost:8080/ahp", None)?
/// )
/// .await?
/// .with_capabilities(vec![
/// ("memory_search".into(), serde_json::json!({
/// "type": "http",
/// "url": "http://localhost:8080/memory/search"
/// })),
/// ("session_info".into(), serde_json::json!({
/// "type": "query",
/// "handler": "get_session_info"
/// })),
/// ]);
/// # Ok(())
/// # }
/// ```
pub fn with_capabilities(
mut self,
capabilities: impl IntoIterator<Item = (String, serde_json::Value)>,
) -> Self {
for (key, value) in capabilities {
self.capabilities.insert(key, value);
}
self
}
/// Add a single capability
pub fn add_capability(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.capabilities.insert(key.into(), value);
self
}
/// Record an error for session stats.
pub fn record_error(&self) {
self.error_count.fetch_add(1, Ordering::Relaxed);
}
/// Get total events processed.
pub fn total_events_count(&self) -> u64 {
self.total_events.load(Ordering::Relaxed)
}
/// Get error count.
pub fn error_count_value(&self) -> u64 {
self.error_count.load(Ordering::Relaxed)
}
/// Get idle duration in milliseconds.
pub fn get_idle_duration_ms(&self) -> u64 {
let last = self.last_activity.load(Ordering::Relaxed);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
now.saturating_sub(last)
}
/// Check if agent is idle and create idle event if threshold exceeded.
pub fn check_idle(&self) -> Option<IdleEvent> {
let elapsed = self.get_idle_duration_ms();
if elapsed >= self.idle_threshold_ms {
Some(IdleEvent {
idle_duration_ms: elapsed,
idle_reason: "no_activity".to_string(),
last_event_type: None,
suggested_action: Some("dream".to_string()),
})
} else {
None
}
}
/// Set memory summary for context population.
///
/// This allows the executor to include memory statistics in the EventContext.
pub fn set_memory_summary(self: Arc<Self>, summary: a3s_ahp::MemorySummary) {
let mut lock = self.memory_summary.write().unwrap();
*lock = Some(summary);
}
/// Set current task description for context population.
///
/// This allows the executor to include the current task in the EventContext.
pub fn set_current_task(self: Arc<Self>, task: String) {
let mut lock = self.current_task.write().unwrap();
*lock = Some(task);
}
/// Add a recent fact for context population.
///
/// Facts are used for Retrieve intent in ContextPerception events.
pub fn add_recent_fact(self: Arc<Self>, fact: a3s_ahp::Fact) {
let mut lock = self.recent_facts.write().unwrap();
lock.push(fact);
}
/// Set recent facts for context population (replaces existing facts).
///
/// Facts are used for Retrieve intent in ContextPerception events.
pub fn set_recent_facts(self: Arc<Self>, facts: Vec<a3s_ahp::Fact>) {
let mut lock = self.recent_facts.write().unwrap();
*lock = facts;
}
/// Get a clone of recent facts.
pub fn get_recent_facts(&self) -> Vec<a3s_ahp::Fact> {
self.recent_facts.read().unwrap().clone()
}
/// Set workspace path for context population.
///
/// This allows the executor to include the current workspace in the EventContext.
pub fn set_workspace(self: Arc<Self>, workspace: String) {
let mut lock = self.workspace.write().unwrap();
*lock = Some(workspace);
}
/// Get workspace path.
pub fn get_workspace(&self) -> Option<String> {
self.workspace.read().unwrap().clone()
}
/// Send a query to the harness and wait for response.
///
/// This allows the agent to request guidance or information from the harness.
/// Used for clarify actions, request approvals, or query harness knowledge.
pub async fn query(
&self,
query_type: impl Into<String>,
payload: serde_json::Value,
) -> Result<a3s_ahp::QueryResponse, a3s_ahp::AhpError> {
self.client.query(query_type, payload).await
}
/// Send a batch of events to the harness.
///
/// This allows non-blocking events to be batched for efficiency.
/// The harness processes them and returns a batch response.
pub async fn send_batch(
&self,
events: Vec<a3s_ahp::AhpEvent>,
) -> Result<a3s_ahp::BatchResponse, a3s_ahp::AhpError> {
self.client.send_batch(events).await
}
/// Enable batch processing for non-blocking events.
///
/// When enabled, non-blocking events are accumulated and sent in batches
/// either when batch_size is reached or batch_timeout_ms expires.
pub fn with_batch_config(mut self, batch_size: usize, batch_timeout_ms: u64) -> Self {
self.batch_size = batch_size;
self.batch_timeout_ms = batch_timeout_ms;
self.batch_enabled = true;
self
}
/// Add an event to the batch buffer.
///
/// Returns true if the batch should be flushed (size threshold reached).
pub async fn add_to_batch(&self, event: a3s_ahp::AhpEvent) -> bool {
let should_flush = {
let mut buffer = self.batch_buffer.write().unwrap();
buffer.push(event);
buffer.len() >= self.batch_size
};
if should_flush {
self.flush_batch().await;
}
should_flush
}
/// Flush the batch buffer and send all events.
pub async fn flush_batch(&self) {
let events = {
let mut buffer = self.batch_buffer.write().unwrap();
if buffer.is_empty() {
return;
}
std::mem::take(&mut *buffer)
};
if !events.is_empty() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
self.last_batch_flush.store(now, Ordering::Relaxed);
match self.client.send_batch(events).await {
Ok(_) => {
debug!("Batch sent successfully");
}
Err(e) => {
warn!("Batch send failed: {}", e);
}
}
}
}
/// Check if batch timeout has expired and flush if needed.
pub async fn check_batch_timeout(&self) {
let elapsed = {
let last = self.last_batch_flush.load(Ordering::Relaxed);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
now.saturating_sub(last)
};
if elapsed >= self.batch_timeout_ms {
self.flush_batch().await;
}
}
/// Start background tasks for heartbeat and idle detection.
///
/// This method spawns two background Tokio tasks:
/// - Heartbeat: sends HeartbeatEvent every 60 seconds
/// - Idle detection: checks idle state every 5 seconds, fires IdleEvent if threshold exceeded
///
/// The tasks run until the shutdown signal is set or the executor is dropped.
///
/// # Example
///
/// ```rust,no_run
/// use a3s_code_core::ahp::{AhpHookExecutor, AhpTransport};
///
/// # async fn example() -> anyhow::Result<()> {
/// let executor = AhpHookExecutor::new(
/// AhpTransport::http("http://localhost:8080/ahp", None)
/// ).await?;
///
/// // Start background heartbeat and idle detection
/// executor.execute_background();
///
/// // Executor is now supervised in the background
/// # Ok(())
/// # }
/// ```
pub fn execute_background(self: Arc<Self>) {
let shutdown = Arc::clone(&self.shutdown);
shutdown.store(false, Ordering::Relaxed);
// Spawn heartbeat task
let heartbeat_executor = Arc::clone(&self);
let heartbeat_shutdown = Arc::clone(&shutdown);
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(60));
loop {
tokio::select! {
_ = interval.tick() => {
if heartbeat_shutdown.load(Ordering::Relaxed) {
debug!("Heartbeat task shutting down");
break;
}
let event = AhpEvent {
event_type: EventType::Heartbeat,
session_id: heartbeat_executor.agent_id.clone(),
agent_id: heartbeat_executor.agent_id.clone(),
timestamp: Utc::now().to_rfc3339(),
depth: heartbeat_executor.depth,
payload: serde_json::to_value(HeartbeatEvent {
uptime_ms: heartbeat_executor.start_time.elapsed().as_millis() as u64,
total_events_processed: heartbeat_executor.total_events.load(Ordering::Relaxed),
current_state: "active".to_string(),
cpu_percent: None,
memory_bytes: None,
active_tools: None,
pending_actions: None,
queue_depth: None,
tokens_used: None,
}).unwrap_or_default(),
context: heartbeat_executor.build_context(),
metadata: None,
};
if let Err(e) = heartbeat_executor.client.send_event(event.event_type.clone(), event.payload.clone()).await {
warn!("Heartbeat failed: {}", e);
}
}
}
}
});
// Spawn idle detection task
let idle_executor = Arc::clone(&self);
let idle_shutdown = Arc::clone(&shutdown);
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(5));
loop {
tokio::select! {
_ = interval.tick() => {
if idle_shutdown.load(Ordering::Relaxed) {
debug!("Idle detection task shutting down");
break;
}
if let Some(idle_event) = idle_executor.check_idle() {
debug!("Idle detected, sending IdleEvent");
let event = AhpEvent {
event_type: EventType::Idle,
session_id: idle_executor.agent_id.clone(),
agent_id: idle_executor.agent_id.clone(),
timestamp: Utc::now().to_rfc3339(),
depth: idle_executor.depth,
payload: serde_json::to_value(idle_event).unwrap_or_default(),
context: idle_executor.build_context(),
metadata: None,
};
// Wait for idle decision (blocking)
match idle_executor.client.send_event(event.event_type.clone(), event.payload.clone()).await {
Ok(decision_payload) => {
debug!("Idle decision: {:?}", decision_payload);
// Try to parse as IdleDecision first, then fall back to generic Decision
if let Ok(idle_decision) = serde_json::from_value::<a3s_ahp::IdleDecision>(decision_payload.clone()) {
match idle_decision {
a3s_ahp::IdleDecision::Defer { .. } => {
// Increase threshold temporarily
}
_ => {
// Reset idle detection
idle_executor.update_activity();
}
}
} else if let Ok(decision) = serde_json::from_value::<a3s_ahp::Decision>(decision_payload) {
match decision {
a3s_ahp::Decision::Defer { .. } => {
// Increase threshold temporarily
}
_ => {
// Reset idle detection
idle_executor.update_activity();
}
}
}
}
Err(e) => {
warn!("Idle decision failed: {}", e);
}
}
}
}
}
}
});
}
/// Stop background tasks (heartbeat and idle detection).
///
/// This signals the background tasks to shut down gracefully.
pub fn stop_background(&self) {
self.shutdown.store(true, Ordering::Relaxed);
}
/// Get the agent ID
pub fn agent_id(&self) -> &str {
&self.agent_id
}
/// Get the depth
pub fn depth(&self) -> u32 {
self.depth
}
/// Get idle threshold in milliseconds
pub fn idle_threshold(&self) -> u64 {
self.idle_threshold_ms
}
/// Update last activity timestamp
fn update_activity(&self) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
self.last_activity.store(now, Ordering::Relaxed);
}
/// Increment event counter and update activity
fn record_event(&self) {
self.total_events.fetch_add(1, Ordering::Relaxed);
self.update_activity();
}
/// Map A3S Code hook event to AHP event
fn map_event(&self, event: &HookEvent) -> Option<AhpEvent> {
let (event_type, payload) = match event {
HookEvent::PreToolUse(e) => (
EventType::PreAction,
serde_json::json!({
"tool": e.tool,
"arguments": e.args,
"working_directory": e.working_directory,
"recent_tools": e.recent_tools,
}),
),
HookEvent::PostToolUse(e) => (
EventType::PostAction,
serde_json::json!({
"tool": e.tool,
"arguments": e.args,
"result": {
"success": e.result.success,
"output": e.result.output,
"exit_code": e.result.exit_code,
"duration_ms": e.result.duration_ms,
}
}),
),
HookEvent::PrePrompt(e) => (
EventType::PrePrompt,
serde_json::json!({
"prompt": e.prompt,
"system_prompt": e.system_prompt,
"message_count": e.message_count,
}),
),
HookEvent::GenerateStart(e) => (
EventType::PrePrompt,
serde_json::json!({
"prompt": e.prompt,
"session_id": e.session_id,
}),
),
HookEvent::PostResponse(e) => (
EventType::PostAction,
serde_json::json!({
"response_text": e.response_text,
"tool_calls_count": e.tool_calls_count,
"usage": e.usage,
"duration_ms": e.duration_ms,
}),
),
HookEvent::SessionStart(e) => (
EventType::SessionStart,
serde_json::json!({
"session_id": e.session_id,
"system_prompt": e.system_prompt,
"model_provider": e.model_provider,
"model_name": e.model_name,
}),
),
HookEvent::SessionEnd(e) => (
EventType::SessionEnd,
serde_json::json!({
"session_id": e.session_id,
"duration_ms": e.duration_ms,
}),
),
HookEvent::OnError(e) => (
EventType::Error,
serde_json::json!({
"error_type": format!("{:?}", e.error_type),
"error_message": e.error_message,
"context": e.context,
}),
),
// Context perception events
HookEvent::PreContextPerception(e) => {
let workspace = self.workspace.read().unwrap().clone().unwrap_or_default();
(
EventType::ContextPerception,
serde_json::json!({
"intent": e.intent,
"target_type": e.target_type,
"target_name": e.target_name,
"domain": e.domain,
"query": e.query,
"working_directory": workspace,
"urgency": e.urgency,
}),
)
}
HookEvent::PostContextPerception(e) => (
EventType::ContextPerception,
serde_json::json!({
"intent": e.intent,
"target_type": e.target_type,
"success": e.success,
"facts_retrieved": e.facts_retrieved,
"files_retrieved": e.files_retrieved,
"error": e.error,
}),
),
// Success event
HookEvent::OnSuccess(e) => (
EventType::Success,
serde_json::json!({
"action_type": e.action_type,
"action_summary": e.action_summary,
"duration_ms": e.duration_ms,
}),
),
// Memory recall events
HookEvent::PreMemoryRecall(e) => (
EventType::MemoryRecall,
serde_json::json!({
"query": e.query,
"memory_type": e.memory_type,
"max_results": e.max_results,
"working_directory": e.working_directory,
}),
),
HookEvent::PostMemoryRecall(e) => (
EventType::MemoryRecall,
serde_json::json!({
"query": e.query,
"memory_type": e.memory_type,
"facts_retrieved": e.facts_retrieved,
"success": e.success,
"error": e.error,
}),
),
// Planning events
HookEvent::PrePlanning(e) => (
EventType::Planning,
serde_json::json!({
"task_description": e.task_description,
"available_strategies": e.available_strategies,
"constraints": e.constraints,
}),
),
HookEvent::PostPlanning(e) => (
EventType::Planning,
serde_json::json!({
"task_description": e.task_description,
"strategy_used": e.strategy_used,
"subtasks": e.subtasks,
"success": e.success,
"error": e.error,
}),
),
// Reasoning events
HookEvent::PreReasoning(e) => (
EventType::Reasoning,
serde_json::json!({
"reasoning_type": format!("{:?}", e.reasoning_type),
"problem_statement": e.problem_statement,
"hints": e.hints,
}),
),
HookEvent::PostReasoning(e) => (
EventType::Reasoning,
serde_json::json!({
"reasoning_type": format!("{:?}", e.reasoning_type),
"conclusion": e.conclusion,
"steps_count": e.steps_count,
"success": e.success,
"error": e.error,
}),
),
// Rate limit event
HookEvent::OnRateLimit(e) => (
EventType::RateLimit,
serde_json::json!({
"limit_type": format!("{:?}", e.limit_type),
"retry_after_ms": e.retry_after_ms,
"current_usage": e.current_usage,
}),
),
// Confirmation event
HookEvent::OnConfirmation(e) => (
EventType::Confirmation,
serde_json::json!({
"confirmation_type": format!("{:?}", e.confirmation_type),
"message": e.message,
"options": e.options,
}),
),
// Intent detection event
HookEvent::IntentDetection(e) => (
EventType::IntentDetection,
serde_json::json!({
"prompt": e.prompt,
"workspace": e.workspace,
"language_hint": e.language_hint,
}),
),
// GenerateEnd maps to PostAction (fire-and-forget)
HookEvent::GenerateEnd(e) => (
EventType::PostAction,
serde_json::json!({
"response_text": e.response_text,
"tool_calls": e.tool_calls,
"usage": e.usage,
"duration_ms": e.duration_ms,
}),
),
// Skill events not mapped to AHP (no equivalent control point)
HookEvent::SkillLoad(_) | HookEvent::SkillUnload(_) => {
return None;
}
};
Some(AhpEvent {
event_type,
session_id: self.extract_session_id(event),
agent_id: self.agent_id.clone(),
timestamp: Utc::now().to_rfc3339(),
depth: self.depth,
payload,
context: self.build_context(),
metadata: None,
})
}
/// Build EventContext with client自主 exposes capabilities.
///
/// The capabilities field is always populated if any capabilities were set.
/// Session stats are populated from the executor's tracked data.
/// Memory summary and current task are populated if set via setter methods.
fn build_context(&self) -> Option<a3s_ahp::EventContext> {
// Always include capabilities if any were set
if self.capabilities.is_empty() {
return None;
}
// Build session stats from tracked data
let session_stats = SessionStats {
total_actions: self.total_events.load(Ordering::Relaxed) as usize,
total_tokens: self.total_tokens.load(Ordering::Relaxed),
duration_ms: self.start_time.elapsed().as_millis() as u64,
error_count: self.error_count.load(Ordering::Relaxed) as usize,
};
// Get optional memory summary
let memory_summary = self.memory_summary.read().unwrap().clone();
// Get optional current task
let current_task = self.current_task.read().unwrap().clone();
// Get recent facts
let recent_facts = self.recent_facts.read().unwrap().clone();
Some(a3s_ahp::EventContext {
recent_facts: Some(recent_facts),
memory_summary,
session_stats: Some(session_stats),
current_task,
capabilities: Some(self.capabilities.clone()),
})
}
/// Extract session ID from hook event
fn extract_session_id(&self, event: &HookEvent) -> String {
match event {
HookEvent::PreToolUse(e) => e.session_id.clone(),
HookEvent::PostToolUse(e) => e.session_id.clone(),
HookEvent::GenerateStart(e) => e.session_id.clone(),
HookEvent::SessionStart(e) => e.session_id.clone(),
HookEvent::SessionEnd(e) => e.session_id.clone(),
HookEvent::PrePrompt(e) => e.session_id.clone(),
HookEvent::PreContextPerception(e) => e.session_id.clone(),
HookEvent::PostContextPerception(e) => e.session_id.clone(),
HookEvent::OnSuccess(e) => e.session_id.clone(),
HookEvent::PreMemoryRecall(e) => e.session_id.clone(),
HookEvent::PostMemoryRecall(e) => e.session_id.clone(),
HookEvent::PrePlanning(e) => e.session_id.clone(),
HookEvent::PostPlanning(e) => e.session_id.clone(),
HookEvent::PreReasoning(e) => e.session_id.clone(),
HookEvent::PostReasoning(e) => e.session_id.clone(),
HookEvent::OnRateLimit(e) => e.session_id.clone(),
HookEvent::OnConfirmation(e) => e.session_id.clone(),
HookEvent::IntentDetection(e) => e.session_id.clone(),
// Skill events are global (not session-specific)
HookEvent::SkillLoad(_) => String::new(),
HookEvent::SkillUnload(_) => String::new(),
// Other events
HookEvent::GenerateEnd(_) | HookEvent::PostResponse(_) | HookEvent::OnError(_) => {
self.agent_id.clone()
}
}
}
/// Map AHP decision to hook result based on event type.
///
/// For specialized event types (ContextPerception, MemoryRecall, Planning,
/// Reasoning, RateLimit, Confirmation), the decision_payload is deserialized
/// into the appropriate specialized decision type.
fn map_decision(
&self,
event_type: EventType,
decision_payload: serde_json::Value,
) -> HookResult {
match event_type {
EventType::ContextPerception => self.map_context_perception_decision(&decision_payload),
EventType::MemoryRecall => self.map_memory_recall_decision(&decision_payload),
EventType::Planning => self.map_planning_decision(&decision_payload),
EventType::Reasoning => self.map_reasoning_decision(&decision_payload),
EventType::RateLimit => self.map_rate_limit_decision(&decision_payload),
EventType::Confirmation => self.map_confirmation_decision(&decision_payload),
EventType::IntentDetection => self.map_intent_detection_decision(&decision_payload),
_ => self.map_generic_decision(decision_payload),
}
}
/// Map generic AHP decision to hook result
fn map_generic_decision(&self, payload: serde_json::Value) -> HookResult {
match serde_json::from_value::<Decision>(payload) {
Ok(Decision::Allow {
modified_payload, ..
}) => {
if let Some(modified) = modified_payload {
HookResult::Continue(Some(modified))
} else {
HookResult::Continue(None)
}
}
Ok(Decision::Block { reason, .. }) => HookResult::Block(reason),
Ok(Decision::Defer {
retry_after_ms,
reason,
}) => {
if let Some(r) = reason {
debug!("AHP defer: {}", r);
}
HookResult::Retry(retry_after_ms)
}
Ok(Decision::Modify {
modified_payload, ..
}) => HookResult::Continue(Some(modified_payload)),
Ok(Decision::Escalate {
reason,
escalation_target,
}) => HookResult::Escalate {
reason,
target: escalation_target,
},
Err(_) => HookResult::Block("Invalid decision payload".into()),
}
}
/// Map ContextPerception decision to hook result
fn map_context_perception_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<ContextPerceptionDecision>(payload.clone()) {
Ok(ContextPerceptionDecision::Allow {
injected_context, ..
}) => {
let value = serde_json::to_value(injected_context).ok();
HookResult::Continue(value)
}
Ok(ContextPerceptionDecision::Block { reason, .. }) => HookResult::Block(reason),
Ok(ContextPerceptionDecision::Refine {
refined_intent,
refined_target,
scope_hints,
}) => HookResult::Continue(Some(serde_json::json!({
"refined_intent": refined_intent,
"refined_target": refined_target,
"scope_hints": scope_hints
}))),
Err(_) => {
// Fallback to generic decision parsing
self.map_generic_decision(payload.clone())
}
}
}
/// Map MemoryRecall decision to hook result
fn map_memory_recall_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<MemoryRecallDecision>(payload.clone()) {
Ok(MemoryRecallDecision::Allow { injected_facts, .. }) => {
let value = serde_json::to_value(injected_facts).ok();
HookResult::Continue(value)
}
Ok(MemoryRecallDecision::Block { reason, .. }) => HookResult::Block(reason),
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Map Planning decision to hook result
fn map_planning_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<PlanningDecision>(payload.clone()) {
Ok(PlanningDecision::Allow {
selected_strategy,
planning_template,
..
}) => HookResult::Continue(Some(serde_json::json!({
"selected_strategy": selected_strategy,
"planning_template": planning_template
}))),
Ok(PlanningDecision::Block { reason, .. }) => HookResult::Block(reason),
Ok(PlanningDecision::Modify {
modified_task,
hints,
}) => HookResult::Continue(Some(serde_json::json!({
"modified_task": modified_task,
"hints": hints
}))),
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Map Reasoning decision to hook result
fn map_reasoning_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<ReasoningDecision>(payload.clone()) {
Ok(ReasoningDecision::Allow { hints, .. }) => {
let value = serde_json::to_value(hints).ok();
HookResult::Continue(value)
}
Ok(ReasoningDecision::Block { reason, .. }) => HookResult::Block(reason),
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Map RateLimit decision to hook result
fn map_rate_limit_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<RateLimitDecision>(payload.clone()) {
Ok(RateLimitDecision::Retry { retry_after_ms, .. }) => {
HookResult::Retry(retry_after_ms)
}
Ok(RateLimitDecision::Queue) => HookResult::Skip,
Ok(RateLimitDecision::Skip { .. }) => HookResult::Skip,
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Map Confirmation decision to hook result
fn map_confirmation_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<ConfirmationDecision>(payload.clone()) {
Ok(ConfirmationDecision::Escalate) => HookResult::Escalate {
reason: "Human confirmation required".into(),
target: None,
},
Ok(ConfirmationDecision::Approve) => HookResult::continue_(),
Ok(ConfirmationDecision::Reject { reason }) => HookResult::Block(reason),
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Map IntentDetection decision to hook result
fn map_intent_detection_decision(&self, payload: &serde_json::Value) -> HookResult {
match serde_json::from_value::<IntentDetectionDecision>(payload.clone()) {
Ok(IntentDetectionDecision::Allow {
detected_intent,
confidence,
target_hints,
}) => HookResult::Continue(Some(serde_json::json!({
"detected_intent": detected_intent,
"confidence": confidence,
"target_hints": target_hints
}))),
Ok(IntentDetectionDecision::Block { reason, .. }) => HookResult::Block(reason),
Err(_) => self.map_generic_decision(payload.clone()),
}
}
/// Check if event type requires blocking (synchronous) response
fn is_blocking_event(&self, event_type: HookEventType) -> bool {
matches!(
event_type,
HookEventType::PreToolUse
| HookEventType::PrePrompt
| HookEventType::GenerateStart
| HookEventType::PreContextPerception
| HookEventType::PreMemoryRecall
| HookEventType::PrePlanning
| HookEventType::PreReasoning
| HookEventType::OnConfirmation
| HookEventType::IntentDetection
)
}
}
#[async_trait]
impl HookExecutor for AhpHookExecutor {
async fn fire(&self, event: &HookEvent) -> HookResult {
// Record this event (updates activity timestamp and counter)
self.record_event();
// Track tokens from PostResponse and GenerateEnd events
match event {
HookEvent::PostResponse(e) => {
self.total_tokens
.fetch_add(e.usage.total_tokens, Ordering::Relaxed);
}
HookEvent::GenerateEnd(e) => {
self.total_tokens
.fetch_add(e.usage.total_tokens, Ordering::Relaxed);
}
_ => {}
}
// Map to AHP event
let ahp_event = match self.map_event(event) {
Some(e) => e,
None => {
// Event not mapped to AHP, allow by default
debug!("Event {:?} not mapped to AHP, allowing", event.event_type());
return HookResult::Continue(None);
}
};
// Check if this is a blocking event
let is_blocking = self.is_blocking_event(event.event_type());
if is_blocking {
// Flush any pending batch before sending blocking event
if self.batch_enabled {
self.flush_batch().await;
}
// Send event and wait for decision
match self
.client
.send_event(ahp_event.event_type.clone(), ahp_event.payload.clone())
.await
{
Ok(decision_payload) => {
debug!(
"AHP decision for {:?}: {:?}",
ahp_event.event_type, decision_payload
);
self.map_decision(ahp_event.event_type, decision_payload)
}
Err(e) => {
warn!("AHP error: {}, allowing by default", e);
HookResult::Continue(None)
}
}
} else if self.batch_enabled {
// Batch mode: accumulate non-blocking events
self.add_to_batch(ahp_event).await;
HookResult::Continue(None)
} else {
// Fire-and-forget for non-blocking events (legacy behavior)
let client = self.client.clone();
let event = ahp_event;
tokio::spawn(async move {
if let Err(e) = client
.send_event(event.event_type.clone(), event.payload.clone())
.await
{
warn!("AHP fire-and-forget error: {}", e);
}
});
HookResult::Continue(None)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hooks::PreToolUseEvent;
fn make_test_executor() -> AhpHookExecutor {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
AhpHookExecutor {
client: Arc::new(unsafe { std::mem::zeroed() }),
agent_id: "test-agent".to_string(),
depth: 0,
last_activity: Arc::new(AtomicU64::new(now)),
idle_threshold_ms: 10_000,
start_time: Instant::now(),
total_events: Arc::new(AtomicU64::new(0)),
total_tokens: Arc::new(AtomicI32::new(0)),
error_count: Arc::new(AtomicU64::new(0)),
capabilities: HashMap::new(),
shutdown: Arc::new(AtomicBool::new(false)),
memory_summary: Arc::new(RwLock::new(None)),
current_task: Arc::new(RwLock::new(None)),
recent_facts: Arc::new(RwLock::new(Vec::new())),
workspace: Arc::new(RwLock::new(None)),
batch_buffer: Arc::new(RwLock::new(Vec::new())),
batch_size: 10,
batch_timeout_ms: 5000,
last_batch_flush: Arc::new(AtomicU64::new(now)),
batch_enabled: false,
}
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_map_pre_tool_use() {
let executor = make_test_executor();
let event = HookEvent::PreToolUse(PreToolUseEvent {
session_id: "session-123".to_string(),
tool: "Bash".to_string(),
args: serde_json::json!({"command": "ls"}),
working_directory: "/workspace".to_string(),
recent_tools: vec![],
});
let ahp_event = executor.map_event(&event).unwrap();
assert_eq!(ahp_event.event_type, EventType::PreAction);
assert_eq!(ahp_event.session_id, "session-123");
assert_eq!(ahp_event.depth, 0);
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_map_decision_allow() {
let executor = make_test_executor();
let decision = Decision::Allow {
modified_payload: None,
metadata: None,
};
let result = executor.map_decision(EventType::PreAction, serde_json::json!({}));
assert!(matches!(result, HookResult::Continue(None)));
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_map_decision_block() {
let executor = make_test_executor();
let decision = Decision::Block {
reason: "Dangerous command".to_string(),
metadata: None,
};
let result = executor.map_decision(EventType::PreAction, serde_json::json!({}));
assert!(matches!(result, HookResult::Block(_)));
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_idle_detection_not_idle() {
let executor = make_test_executor();
// Should not be idle since we just created it
let idle_event = executor.check_idle();
assert!(idle_event.is_none());
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_idle_detection_after_threshold() {
let executor = make_test_executor();
// Simulate old last activity (11 seconds ago)
let old_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64
- 11_000;
executor.last_activity.store(old_time, Ordering::Relaxed);
let idle_event = executor.check_idle();
assert!(idle_event.is_some());
let idle = idle_event.unwrap();
assert!(idle.idle_duration_ms >= 10_000);
assert_eq!(idle.idle_reason, "no_activity");
assert_eq!(idle.suggested_action, Some("dream".to_string()));
}
#[test]
#[ignore] // Requires mock AhpClient - zeroed Arc causes UB
fn test_record_event_updates_activity() {
let executor = make_test_executor();
let before = executor.get_idle_duration_ms();
// Small delay then record
std::thread::sleep(Duration::from_millis(10));
executor.record_event();
let after = executor.get_idle_duration_ms();
// After recording, idle duration should be small (near zero)
assert!(after < before);
}
}